【问题标题】:How can I fix set headers in node js?如何修复节点 js 中的设置标头?
【发布时间】:2018-12-26 23:20:20
【问题描述】:

我正在尝试从 mysql 的条件重定向到 get 方法,但它不起作用。我该如何解决?

app.post('/responses/',(req,res)=>{
    var {text, context ={} } = req.body;
    var params = {
        input: {text},
        workspace_id: '07',
        context
    }`
    `assistant.message(params,(err,response) => {
        if(err){
            res.status(500).json(err);
        }
        else {
            res.json(response);
            console.log(JSON.stringify(response, null, 2));
        }
        if(response.context.rfc){
            var RFC = response.context.rfc;
            connection.connect(function(err) {
                if (err) throw err;
                connection.query(`SELECT * FROM test where RFC = '${RFC}'`, function (err, result, fields) {
                    if(result.length){
                        console.log("login");
                    }
                    else {
                        console.log('no login');
                        res.redirect('/home'); //Her not redirect.
                    }
                });
            });
        }
    });
});

因为显示这个错误:hrow err; // Rethrow non-MySQL errors ^Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

【问题讨论】:

标签: javascript node.js


【解决方案1】:

错误消息表明您正在尝试在响应已发送后设置标头。从您的示例代码看来,您的 API 调用(无论 assistant.message 是什么)正在返回 RFC。然后您尝试重定向到另一个页面,但您已经调用了res.json,它开始向浏览器发送响应。

您需要稍微重构您的控制器,以便您只调用 res.redirectres.json,而不是同时调用两者。

【讨论】:

  • Nelson 我如何使用其他资源?
  • 发送后不能设置任何标题或再次发送资源。
  • 您需要重新排列您的 if/else 语句,以便只有在您没有重定向或返回错误时才进入res.json响应。
猜你喜欢
  • 2015-04-06
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多