使用Express与body-parser无法读取AJAX传递的表单参数
Let's walk through the common issues and fixes step by step to get your form data showing up on the server side.
1. Correct Your AJAX Request
The main missing piece in your current AJAX code is setting the proper Content-Type header (unless you're using FormData, but let's cover both cases). Also, ensure you're sending data in a format Express can parse.
Option A: Sending URL-Encoded Form Data (most common for traditional forms)
Update your ajaxCallPost function to format the params correctly and set the header:
function ajaxCallPost(url, elementid, params) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById(elementid).innerHTML = xhttp.responseText; } }; xhttp.open("POST", url, true); // Use async (true) instead of false for better practice // Set the content type for URL-encoded data xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Convert params object to URL-encoded string var encodedParams = Object.keys(params).map(key => encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) ).join("&"); xhttp.send(encodedParams); }
Note: Using async: true (the default) is better than synchronous requests (false) because it doesn't block the browser.
Option B: Sending FormData (for file uploads or complex forms)
If you're using HTML5 FormData, you don't need to set the Content-Type header (the browser handles it automatically):
function ajaxCallPost(url, elementid, formData) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById(elementid).innerHTML = xhttp.responseText; } }; xhttp.open("POST", url, true); // No need to set Content-Type here xhttp.send(formData); } // Usage example: // const form = document.getElementById("your-form"); // ajaxCallPost("/submit", "result", new FormData(form));
2. Configure Express.js & body-parser Correctly
Make sure your server is set up to parse the incoming data format you're sending.
First, install dependencies if you haven't:
npm install express body-parser
Then, set up your Express server:
const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // Parse URL-encoded form data (for Option A above) app.use(bodyParser.urlencoded({ extended: true })); // If you're sending JSON data instead, add this line: // app.use(bodyParser.json()); // Handle POST request app.post('/submit', (req, res) => { // Now req.body should contain your form data! console.log("Received data:", req.body); res.send("Data received: " + JSON.stringify(req.body)); }); app.listen(3000, () => { console.log("Server running on port 3000"); });
Key note: The extended: true option allows parsing of nested objects in the form data, which is almost always what you want.
3. Verify the Request (Optional but Helpful)
If you're still having issues, use your browser's DevTools (Network tab) to check the POST request:
- Look at the Headers tab to confirm the Content-Type matches what you're sending.
- Check the Form Data or Payload tab to ensure the data is being sent correctly.
That should fix the problem—your server should now receive and log the form data from your AJAX request!
内容的提问来源于stack exchange,提问作者Sohel Shaikh

