gpt4 book ai didi

node.js - 为什么重定向后无法设置 header ?

转载 作者:太空宇宙 更新时间:2023-11-04 02:47:13 24 4
gpt4 key购买 nike

这是我在expressjs(node)中发出json请求后的回调

function question(req, res){
request(req, res, function(response){
//redirect to the right url if page doesn't exist.
var params = app.req.params;
if(params.questionId && encodeURIComponent(params.slug) !== response.question.slug){
app.res.redirect(response.question.url);
}
//Render question
app.res.render('master',response);
});
}

这是请求:

function request(req, res, callback){
app.req = req;
app.res = res;
http.get({
hostname: 'localhost',
port: 80,
path: req.url,
agent: false // create a new agent just for this one request
}, function(response){
response.setEncoding('utf8');
response.on('data', function(json){
json = JSON.parse(json);
console.log(json)
callback(json);
});
});
}

如果我触发 res.redirect 我会收到以下错误。我的期望是我被重定向到新的 url 并且 app.res.render 应该被渲染。无论我访问哪个网址,此错误都会持续触发一段时间。

_http_outgoing.js:344

throw new Error('Can\'t set headers after they are sent.');
^

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (/Users/kristoffer/web/zenqa2.1/node_modules/express/lib/response.js:718:10)
at ServerResponse.send (/Users/kristoffer/web/zenqa2.1/node_modules/express/lib/response.js:163:12)
at done (/Users/kristoffer/web/zenqa2.1/node_modules/express/lib/response.js:957:10)
at /Users/kristoffer/web/zenqa2.1/node_modules/mustache-express/mustache-express.js:168:5
at /Users/kristoffer/web/zenqa2.1/node_modules/mustache-express/mustache-express.js:131:10
at /Users/kristoffer/web/zenqa2.1/node_modules/mustache-express/mustache-express.js:118:11
at loadAllPartials (/Users/kristoffer/web/zenqa2.1/node_modules/mustache-express/mustache-express.js:79:10)
at /Users/kristoffer/web/zenqa2.1/node_modules/mustache-express/mustache-express.js:102:10
at /Users/kristoffer/web/zenqa2.1/node_modules/async/lib/async.js:232:13

最佳答案

对于单个请求,只会发送一个响应,并且您必须在发送响应之前设置 header 。 app.res.redirectapp.res.render 用于传递响应。所以实际上你只能使用其中之一。使用return退出代码或使用else条件。

function question(req, res){
request(req, res, function(response){
//redirect to the right url if page doesn't exist.
var params = app.req.params;
if(params.questionId && encodeURIComponent(params.slug) !== response.question.slug){
return app.res.redirect(response.question.url); // return
}
// also you can use else condition here
app.res.render('master',response);
});
}

关于node.js - 为什么重定向后无法设置 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35014252/

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