Axios GET请求携带JSON时服务端req.body为空的问题排查
Hey there, let's break down why your JSON payload isn't reaching your Node.js backend, and how to fix it properly.
What's Going Wrong Here?
First off, there are two key issues at play:
- GET requests aren't meant to carry request bodies — While the HTTP spec technically doesn't ban this, it's against RESTful best practices, and most backend frameworks (like Express) ignore GET request bodies by default. That's why Postman might work (it's more permissive), but your Node.js setup doesn't pick up
req.body. - Your Axios syntax is incorrect — When using
axios.get(), the second parameter is a config object. You tried passing your data directly as a top-level property, but any request body data needs to be nested under thedatakey in that config object.
The Proper Solutions
Option 1: Use Query Parameters (Recommended)
This is the standard, REST-compliant way to pass data with GET requests. Your backend will access the data via req.query instead of req.body.
Updated React Frontend Code:
async function getConfig() { try { // Pass parameters via the `params` property in the Axios config const retrievedConfig = await axios.get("http://localhost:3000/config/one", { params: { Name: "Hello" } }); console.log(retrievedConfig); } catch (e) { console.log("Error"); console.log(e); } }
Corresponding Node.js (Express) Backend Code:
app.get('/config/one', (req, res) => { // Fetch the value from req.query instead of req.body const requestedName = req.query.Name; // Your logic to fetch the config goes here res.send(/* your response data */); });
Option 2: Force GET Request with Body (Not Recommended)
If you absolutely have to send a body with a GET request (note: this is not ideal and can cause compatibility issues with proxies or other servers), here's how to make it work:
Fixed Axios Frontend Code:
async function getConfig() { try { const retrievedConfig = await axios.get("http://localhost:3000/config/one", { // Nest your payload under the `data` key data: { Name: "Hello" }, headers: { "Content-Type": "application/json" // Remove those Access-Control headers! They belong on the backend response, not your frontend request. } }); console.log(retrievedConfig); } catch (e) { console.log("Error"); console.log(e); } }
Updated Express Backend Configuration:
By default, express.json() only parses bodies for POST/PUT/PATCH/DELETE requests. To make it parse GET bodies, you need to adjust the middleware:
// Replace your existing express.json() line with this app.use(express.json({ type: '*/*' }));
A quick note: Those
Access-Control-Allow-*headers you added to your frontend request? You don't need them there. Those are response headers that your Node.js backend should send to handle CORS, not request headers from your React app. Remove them from your frontend code to avoid confusion.
内容的提问来源于stack exchange,提问作者Darkbound

