我创建了一个小项目。我刚刚添加了一个参数控件,但如果我不发送 id
我会收到此错误。问题出在哪里?
Error: Can't set headers after they are sent
const Express = require('express');
const BodyParser = require('body-parser');
const app = Express();
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({extended: false}));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'POST');
if ('OPTIONS' == req.method) {
res.header('Access-Control-Allow-Methods', 'POST');
return res.send(200);
}
next();
});
app.get('/', (req, res) => {
res.write('Test');
res.end();
});
app.post("/test", (req, res) => {
if (!req.body.id) {
res.send(200).json({code: 400, message: 'error'});
return;
}
})
server = app.listen(8000);
最佳答案
您只需删除.end()
。根据文档(https://expressjs.com/en/api.html#res.end):
Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().
基本上,当您调用 .json()
时,它会发送响应 header ,然后调用 end()
再次发送它们
关于javascript - 错误: Can't set headers after they are sent NodeJs 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56157295/