Express.js处理Postman POST请求:req.body输出异常问题排查
req.body in Express POST Route Hey there, let's dig into why your req.body is showing up as undefined when sending that POST request from Postman! I've run into this exact issue a few times, so here are the most common fixes to check:
1. Postman isn't sending the request as JSON (the #1 culprit!)
Express's express.json() middleware only parses requests where the Content-Type header is set to application/json. If Postman isn't configured correctly, the middleware won't process your body, leaving req.body undefined. Here's how to fix it:
- Open your POST request in Postman
- Go to the Body tab:
- Select Raw from the options
- Use the dropdown menu to choose JSON (not Text, Form-Data, or x-www-form-urlencoded)
- Paste your JSON payload:
{"temp": 97.7, "device": "one"}
- Switch to the Headers tab:
- Make sure there's a header with key
Content-Typeand valueapplication/json(Postman usually adds this automatically when you select JSON, but double-check!)
- Make sure there's a header with key
2. Verify your Express middleware order
Middleware in Express runs in the order you register it. If you had mounted your sensorsRouter before the express.json() middleware, the route handler would run before the body is parsed. Looking at your code, you've got this right:
app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use('/sensors', sensorsRouter);
But just to be safe, confirm there's no other code that reorders these lines in your actual project.
3. Check for conflicting middleware
If you have any other custom middleware or third-party packages registered before your body-parsing middleware, they might be interfering with the request. For example, some logging middleware or CORS middleware could accidentally modify the request stream. Temporarily disable any non-essential middleware to rule this out.
Quick test to confirm
To make sure the parsing is working, update your route handler to send back the body as a response:
router.post('/', function(req, res, next) { console.log(req.body); res.send(req.body); // Send the parsed body back to Postman });
If Postman receives the correct JSON payload in the response, you know the parsing is working and the console issue was just a display quirk (unlikely, but good to rule out!).
Give these steps a try—9 times out of 10, it's just a Postman configuration issue. Let me know if it still doesn't work!
内容的提问来源于stack exchange,提问作者Maxim Neaga

