gpt4 book ai didi

javascript - 错误: Can't set headers after they are sent NodeJs 4

转载 作者:行者123 更新时间:2023-12-02 23:39:05 25 4
gpt4 key购买 nike

我创建了一个小项目。我刚刚添加了一个参数控件,但如果我不发送 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com