简体   繁体   English

NodeJS在下一个请求之前等待HTTP响应

[英]NodeJS wait for HTTP Response before next Request

I'm totally failing with my NodeJS code.我的 NodeJS 代码完全失败了。 I need to make a HTTP Request to an REST API - that API sends me a new URL as response.我需要向 REST API 发出 HTTP 请求 - 该 API 向我发送一个新 URL 作为响应。 After receiving that URL, I need to make an Request to that URL and so on.收到该 URL 后,我需要向该 URL 发出请求等等。

I'm using the我正在使用

var request = require('request');

package.包裹。 The response looks like this:响应如下所示:

{
    "nextURL": "http:// ..."
}

How can I do this?我怎样才能做到这一点? I'm new to the NodeJS world but I already have a lot of experience with JavaScript.我是 NodeJS 世界的新手,但我已经对 JavaScript 有了很多经验。 So therefore it shouldn't be a big problem for me.因此,这对我来说应该不是什么大问题。

I heard and read something about Promises but I don't know if that's the right thing for that.我听说并阅读了一些关于Promises但我不知道这是否适合它。 Please help me!请帮我!

Igues u can make it like this我猜你可以这样

const request = require('request');

    request('https://api.xxx', { json: true }, (err, 
    res, body) => {
      if(response.statusCode === 200) {

         nextUrl(body['nextURL']);
      }

      else (err) {
       return console.log(err); 
      }

    });

    function nextUrl(url){
       request(url, { json: true }, (err, 
       res, body) => {
      if(response.statusCode === 200) {

        //your logic
      }

      else (err) {
       return console.log(err); 
      }

      });
    }

I think you are looking for this我想你正在寻找这个

A Promise is a proxy for a value not necessarily known when the promise is created. Promise 是在创建 Promise 时不一定知道的值的代理。 It allows you to associate handlers to an asynchronous action's eventual success value or failure reason.它允许您将处理程序与异步操作的最终成功值或失败原因相关联。 This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise for the value at some point in the future.这让异步方法可以像同步方法一样返回值:异步方法返回的不是最终值,而是在未来某个时间点返回值的承诺。

var request = require('request-promise');

var baseUrl = 'http://111.111.111.111:8080';

request.post(baseUrl + '/api/auth/login')
.then(function(body) {
    console.log("login OK: " + body);
}).then(function() {
    return request.post(baseUrl + '/api/auth/login'); // <-- inside a function
}).then(function(body) {
    console.log("login OK again: " + body);
}).catch(function (err) {
    console.error(err);
});

I would suggest that you use promisified http client such as axios in the following form我建议您使用 promisified http 客户端,例如以下形式的axios

const axios = require('axios');
axios.get('firstURL')
     .then(firstRes=>{
           return axios.get(firstRes.data.nextURL)
     })
     .then(secondRes=>{
           console.log(secondRes.data)
     })
     .catch(err=>{

     console.log('something went wrong', err);

   })

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

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