为什么我不能在重定向后设置标头?

时间:2016-01-26 12:50:04

标签: node.js express

这是我在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

2 个答案:

答案 0 :(得分:0)

对于单个请求,只会发送一个响应。您必须在发送响应之前设置标头。 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);
    });
}

答案 1 :(得分:-1)

重定向后,您应该阻止任何进一步的代码执行。

http标头定义了cookie等。 如果要设置它们,请在实际关闭http标头之前执行此操作。

在http流中检测到两个以下换行符后,正文将开始。 在身体开始之后,您无法再添加标题信息

只要您使用重定向,它就会将http重定向标头以及htmls主体内的元重定向排队。

相关问题