2017-03-05 43 views
0

後我如何使用Node.js和表達,我想發送POST請求到Web服務器,等待結果,然後將用戶重定向到一個不同的頁面重定向用戶。如何發佈請求完成

我的問題是,POST請求完成之前res.redirect('xxx');得到執行。 而在function res1.on('end', function() { 我不能做res.redirect()

讓我怎麼做的就結束函數重定向?

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'); 

}); 

回答

1

你想做到這一點的回調,讓你知道它的工作:

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"); 
}) 
0

每當響應是從服務器返回的,它進入回調函數所以寫回調的重定向邏輯,你知道它已經完成了。

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'); 

});