[英]Difficulty with making multiple api / http node.js requests
你好我已經有兩個api請求單獨工作但是我很難讓他們都在我的node.js應用程序上工作。 是否有一種簡單的方法可以提出兩個請求? 我已經嘗試過兩個請求將數據放入變量然后渲染它們但我遇到全局變量問題。 任何幫助,將不勝感激。
request(url, function (err, response, body) {
if(err){
res.render('index', {weather: null, error: 'Error, please try again'});
} else {
let weather = JSON.parse(body);
if(weather.main == undefined){
res.render('index', {weather: null, error: 'Error, please try again'});
} else {
if (rain == "0,rain"){
let weatherText = `It's ${weather.main.temp} degrees celsius and with wind speeds of ${weather.wind.speed} mph in ${weather.name} ${weather.sys.country}! & ${weather.weather[0].description}` ;
res.render('index', {weather: weatherText, error: null});
}
else{
let weatherText = `It's ${weather.main.temp} degrees celsius and with wind speeds of ${weather.wind.speed} mph in ${weather.name} ${weather.sys.country}!` ;
res.render('index', {weather: weatherText, error: null});
}
}
}
});
request(url2, function (err, response, body) {
if(err){
res.render('index', {news: null, error: 'Error, please try again'});
} else {
let result = JSON.parse(body);
let news = result.articles[0].title
if(news == undefined){
res.render('index', {news: null, error: 'Error, please try again'});
}
else{
res.render('index', {news:news, error: null});
}
}
})
我會使用“承諾”等到第一次請求收到回復。 一旦發生這種情況,您可以觸發第二個請求,(請參閱下面鏈接中的“然后”)。 在第二個請求返回結果后,您可以在使用數據之前合並兩個請求的響應。
如果請求B需要使用來自請求A的響應的數據,則請求A應該首先在鏈中。 這允許您根據第一個請求調整第二個請求,例如使用IF語句。 如果兩者完全獨立,您可以先選擇要求。
這個鏈接上有一個關於鏈接承諾的部分,它應該與你要做的事情有關: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/然后
有關使用promises和'catch'進行錯誤處理的詳細信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
沒有實際需要使用promises,雖然它們確實簡化了代碼結構,但您可以輕松地嵌套請求:
request(url, function(err, response, body) {
request(url2, function(err2, response2, body2) {
// Both request data is available here
})
})
請注意,回調函數中使用的變量名稱可以在此處更改
如果您有一堆可以獨立運行的請求,請查看promise.all
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.