[英]How to redirect the user after the post request finished
I'm using Node.js and express and I want to send a POST Request to a webserver, wait for the result and then redirect the user to a different page. 我正在使用Node.js进行表达,我想将POST请求发送到Web服务器,等待结果,然后将用户重定向到另一个页面。
My problem is that the res.redirect('xxx');
我的问题是
res.redirect('xxx');
gets executed before the post request is complete. 在发布请求完成之前被执行。 And in the
function res1.on('end', function () {
I can't do a res.redirect()
. 在
function res1.on('end', function () {
我无法执行res.redirect()
。
So how do i do a redirect in the on end function? 那么我该如何在on函数中进行重定向?
app.post('/', function(req,res,next){
console.log(req.body.user);
console.log(req.body.pw);
console.log("-------- POST -------------");
// form data
var postData = querystring.stringify({
grant_type: "password",
client_id: "xxx",
client_secret:"xxx",
username:req.body.user,
password:req.body.pw
});
var options = {
host: 'xxx',
port: 443,
method: 'POST',
path: '/oauth_token.do',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, function (res1) {
result = '';
res1.on('data', function (chunk) {
result += chunk;
});
res1.on('end', function () {
var obj = JSON.parse(result);
console.log(obj.access_token);
access_token = obj.access_token;
});
res1.on('error', function (err) {
console.log("Error 1");
})
});
req.write(postData);
req.end();
// res.redirect('xxx');
});
You wanna do it in the callback so that you know it's done: 您想在回调中执行此操作,以便知道已完成:
res1.on('end', function() {
var obj = JSON.parse(result);
console.log(obj.access_token);
access_token = obj.access_token;
// res.redirect('xxx');
});
res1.on('error', function(err) {
console.log("Error 1");
})
whenever response was returned from the server, it goes to callback function so write your redirect logic in the callback so that you know it's done. 无论何时从服务器返回响应,它都会进入回调函数,因此在回调中编写重定向逻辑,以使您知道已完成。
res1.on('end', function () {
var obj = JSON.parse(result);
console.log(obj.access_token);
access_token = obj.access_token;
//call your redirect function after success response
// res.redirect('xxx');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.