Node.js/Express应用POST请求出现404及响应头设置错误求助
Troubleshooting POST /api/posts 404 + "Can't set headers after they are sent" Error
Hey there, let's work through this issue together—those two errors are probably linked, so we'll tackle them one by one to get your POST endpoint working.
First: Fix the "Can't set headers after they are sent" Error
This error is a dead giveaway that your code is trying to send multiple responses for the same request. Once Express sends a response (like res.send(), res.json(), or res.end()), it locks in the response headers—any attempt to send another response after that will throw this error.
Here are the most common fixes:
- Add
returnafter sending error responses: It's easy to accidentally let code run past a response. For example:// ❌ Bad: Sends two responses if the title is missing app.post('/api/posts', (req, res) => { if (!req.body.title) { res.status(400).send('Title is required'); } res.json({ success: true }); // This triggers the header error }); // ✅ Good: return stops execution after the error response app.post('/api/posts', (req, res) => { if (!req.body.title) { return res.status(400).send('Title is required'); } res.json({ success: true }); }); - Check middlewares for accidental responses: If you have global or route-specific middlewares, make sure none of them call
res.send()/res.json()and then also callnext(). That would send a response early, then let the request continue to your POST route—leading to the header error when the route tries to send another response.
Next: Fix the 404 on POST /api/posts
Once the header error is fixed, let's make sure your POST route is actually being hit:
- Verify the route path matches exactly: Double-check that your POST route is defined as
/api/posts(not/api/postor/posts). Even a single typo will cause a 404. - Check route order: Express matches routes in the order they're registered. If your 404 fallback middleware (like
app.use((req, res) => res.sendStatus(404))) comes before your POST/api/postsroute, Express will hit the 404 first and never reach your endpoint. Move all your specific routes above the 404 fallback. - Check router prefixes (if using
express.Router()): If you're using a router to organize routes, make sure you're mounting it correctly. For example:// If you do this: const postsRouter = express.Router(); postsRouter.post('/posts', (req, res) => { /* ... */ }); app.use('/api', postsRouter); // The actual path becomes /api/posts (correct) // But if you do this by mistake: postsRouter.post('/post', (req, res) => { /* ... */ }); // The path is /api/post, which will 404 when you hit /api/posts
Final Testing Steps
- After fixing the header issue, restart your server.
- Send a test POST request using a tool like curl or Postman:
curl -X POST http://localhost:3000/api/posts -H "Content-Type: application/json" -d '{"title": "Test Post"}' - Check your server logs to see if the POST route handler is being executed (add a
console.log('POST /api/posts hit')at the start of the handler to confirm).
Once you've worked through these steps, your POST endpoint should start working as expected!
内容的提问来源于stack exchange,提问作者SJC




