简体   繁体   English

制作多个api / http node.js请求的难度

[英]Difficulty with making multiple api / http node.js requests

Hello I've gotten two api requests to work individually but I'm having a lot of trouble to get them both working on my node.js app. 你好我已经有两个api请求单独工作但是我很难让他们都在我的node.js应用程序上工作。 Is there an easy way to make two requests ? 是否有一种简单的方法可以提出两个请求? I've tried making two requests putting the data into a variable and then rendering both of them but I run into issues with global variables. 我已经尝试过两个请求将数据放入变量然后渲染它们但我遇到全局变量问题。 Any help would be appreciated. 任何帮助,将不胜感激。

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

I would use a 'promise' to wait until a response has been received from your first request. 我会使用“承诺”等到第一次请求收到回复。 Once this has happened, you can trigger your second request, (see 'then' on the link below). 一旦发生这种情况,您可以触发第二个请求,(请参阅下面链接中的“然后”)。 Once your second request returns a result, you can combine the response from both requests, before using the data. 在第二个请求返回结果后,您可以在使用数据之前合并两个请求的响应。

If request B needs to use data from the response of request A, then request A should be first in the chain. 如果请求B需要使用来自请求A的响应的数据,则请求A应该首先在链中。 This allows you to adjust your second request based on the response from the first eg with IF statements. 这允许您根据第一个请求调整第二个请求,例如使用IF语句。 If the two are completely independent, you can pick either request to go first. 如果两者完全独立,您可以先选择要求。

There is a section on this link about chaining promises, which should be relevant to what you're trying to do: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then 这个链接上有一个关于链接承诺的部分,它应该与你要做的事情有关: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/然后

Details about error handling with promises and 'catch' https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch 有关使用promises和'catch'进行错误处理的详细信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

There is no actual need to use promises, although they do simplify code structure, you can just a easily nest requests: 没有实际需要使用promises,虽然它们确实简化了代码结构,但您可以轻松地嵌套请求:

request(url, function(err, response, body) {
    request(url2, function(err2, response2, body2) {
        // Both request data is available here
    })
})

Note that the variable names used in the callback function can be changed here 请注意,回调函数中使用的变量名称可以在此处更改

Should you have a bunch of requests that can be ran independently, look into promise.all 如果您有一堆可以独立运行的请求,请查看promise.all

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM