【问题标题】:Error: Can't set headers after they are sent NodeJs 4错误:发送标头后无法设置标头 NodeJs 4
【发布时间】:2023-04-01 08:13:01
【问题描述】:

我创建了一个小项目。我刚刚添加了一个参数控件,但是如果我不发送id 我会收到此错误。问题出在哪里?

错误:发送后无法设置标头

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);

【问题讨论】:

  • 当你使用 res.json() 时,默认会断开连接,不需要做 res.end()。 res.json() 和 res.end() 也是一个响应,因此在节点中您只能发送一次响应。发送后无法设置标头:错误意味着您尝试多次发送响应

标签: javascript node.js


【解决方案1】:

您只需删除.end()。根据文档 (https://expressjs.com/en/api.html#res.end):

用于在没有任何数据的情况下快速结束响应。如果你需要 用数据响应,而不是使用诸如 res.send() 和 res.json().

所以基本上,当您调用 .json() 时,它会发送响应标头,然后调用 end() 会再次发送它们

【讨论】:

  • 我删除了 end() 但我得到了同样的错误。 res.status(400).json({code: 400, message: '错误参数'});
猜你喜欢
  • 2017-12-22
  • 2018-09-02
  • 2017-03-03
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
相关资源
最近更新 更多