Express JS处理Ajax请求成功后无法返回数据求助
Hey there, let's work through why your Ajax call isn't getting the response back from Express even though the server is successfully receiving the data. Here are the key issues and fixes:
1. Missing CORS Configuration (Critical for Cross-Domain Requests)
Since your client is making a cross-domain request (crossDomain: true), browsers will block the response unless your Express server explicitly allows it. You need to add CORS middleware to handle this:
Step 1: Install the cors package
npm install cors
Step 2: Update your Express code to enable CORS
const express = require('express'); const path = require('path'); const os = require('os'); const cors = require('cors'); // Import the cors package const app = express(); var bodyParser = require('body-parser'); app.use(cors()); // Add this line before your routes to allow cross-origin requests app.use(bodyParser.json()); app.post('/api/save_user', (req, res) => { Usermodel.saveData(req.body.name, req.body.number) .then(function (userdetail) { res.send({ success: true, data: userdetail }); }) .catch(err => { // Replace generic 'next' with explicit error handling console.error("Save failed:", err); res.status(500).send({ success: false, error: err.message }); }); });
2. Client-side Ajax Tweaks
Your current Ajax setup has two small but impactful issues:
a. Mismatched Data Format with Content-Type
You set contentType: "application/json" but passed a plain JavaScript object as data. jQuery won't automatically stringify it for you in this scenario. Fix it by converting the data to a JSON string:
$.ajax({ url: "http://localhost:8080/api/save_user/", type: "POST", crossDomain: true, data: JSON.stringify({ name: 'Justin', number: '662***' }), // Stringify the data object dataType: "json", contentType: "application/json", success: function (response) { // No need for JSON.parse(response) - dataType: "json" already parses it console.log("Response received:", response); // Use response.data directly here (e.g., display user details) }, error: function (xhr, status, error) { console.error("Request failed:", status, error); alert("Error: " + error); } });
b. Redundant JSON.parse in Success Callback
Since you specified dataType: "json", jQuery automatically parses the server's response into a JavaScript object. Calling JSON.parse(response) will throw an error because you're trying to parse an already parsed object. Just use response directly.
3. Improved Server-side Error Handling
Previously, you used .catch(next) which might not send a meaningful error response back to the client. With the explicit error handling in the updated server code, you ensure failed requests return a proper 500 status code and error message, making debugging much easier.
After applying these changes, your Ajax call should successfully receive the response from the Express server.
内容的提问来源于stack exchange,提问作者Nagaraj M

