2016-09-20 22 views
0

我正在使用async/await(http://stackabuse.com/node-js-async-await-in-es7/並使用bable來轉儲)和請求(https://github.com/request/request)在節點中編寫服務器。我正在嘗試向外部api發出發佈請求並訪問http響應標頭。我只能弄清楚如何訪問我發送的請求。我如何獲得HttpResponse?使用async等待從request.post獲取http響應

下面是代碼

var options = { 
    url: externalUrl, 
    form: body 
}; 

try { 
    var httpResponse = await request.post(options); 
    console.log(httpResponse.headers.location); 
    return "post request succeeded!"; 
} catch (err) { 
    return done(err, null); 
} 
+0

'done(err,null)'?在使用promise和async/await時,不應再使用回調。 – Bergi

回答

0

如果你正在使用請求你不需要異步。

你可以很容易做到這一點:

request({ 
    headers: { 
     'Content-Type': 'application/json', 
    }, 
    uri: url, 
    body: JSON.stringify(options), 
    method: 'POST' 
}, function (err, res, body) { 
    var obj = JSON.parse(body); 
    if(err){ 
     console.log("Ooops: " + err); 
    }else{ 
     console.log(res.headers['content-type']); 
     //Do some stuff with the server response; 
    } 
}); 
0

貌似request與回調執行。 ES7異步/等待僅適用於Promises。您可以使用像bluebird這樣的庫來提供來自request的所有方法。異步/等待應該在之後工作。