2016-03-29 74 views
0

我正在使用请求模块做post请求。发布请求后,我希望重定向用户。但在我看来,我无法在这里重定向。做post请求时无法重定向

function callApi(req, res) { 
    request(options, function(err, response, body){ 
     res.redirect('/'); //cannot read property redirect of undefined, can't set headers after they are sent 
    }); 
} 

function callApi(req, res) { 
    request(options, function(err, response, body){ 
     req.res.redirect('/'); // can't set headers after they are sent 
    }); 
} 
+0

你试过让状态码res.statuscode = 301; ?? –

+0

@DayanMorenoLeon你是什么意思?我只是尝试'req.redirect(301,'/')',它仍然返回相同的结果 – stackdisplay

+0

res.statusCode ='301'; res.redirect( '/');重发('');取决于你使用的快速版本更少的步骤将工作。注意在你的代码中你使用了req.res。应该只是水库。 –

回答

1

里面的回调您的res会引用来自请求回调的响应。这样做...

function callApi(request, response) { 
request(options, function(req, res, body){ 
    response.redirect('/'); //cannot read property redirect of undefined, can't set headers after they are sent 
    }); 
} 

function callApi(request, response) { 
    request(options, function(req, res, body){ 
     response.redirect('/'); // can't set headers after they are sent 
    }); 
} 
+0

由于我更新错误,因此我更新了本主题中的代码。它应该是'request(options,function(error,response,body)'。所以我想这不是问题 – stackdisplay