我正在使用 Node.js 和 Express,我想向网络服务器发送 POST 请求,等待结果,然后将用户重定向到不同的页面。
我的问题是 res.redirect('xxx');
在 post 请求完成之前执行。
并在 function res1.on('end', function () {
我做不到res.redirect()
.
那么我如何在 on end 函数中进行重定向?
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');
});
最佳答案
您想在回调中执行此操作,以便您知道它已完成:
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");
})
关于javascript - post请求完成后如何重定向用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42609541/