简体   繁体   English

请求模块:这是用不同主体发出连续POST请求的正确方法吗?

[英]Request module: Is this the correct way to make consecutive POST requests with different body's?

So I am using the NodeJs "request" module to make multiple post requests, and I feel as though I may be doing it incorrectly. 因此,我正在使用NodeJs的“请求”模块发出多个发布请求,感觉好像我做错了。 Is there a better way to approach this? 有没有更好的方法来解决这个问题?

Lets say I have an array of different JSON bodies I need to send. 可以说我需要发送一系列不同的JSON主体。

        var requests = [
                {
                    "Subject": "TestSubject1",
                    "Body": "TestBody1",
                    "PreferredLanguage": "en-US",
                    "Recipients": [
                        {
                            "FirstName": "TestName1",
                            "EmailAddress": "TestEmail1"
                        }
                    ]
                },
                {
                    "Subject": "TestSubject2",
                    "Body": "TestBody2",
                    "PreferredLanguage": "en-US",
                    "Recipients": [
                        {
                            "FirstName": "TestName2",
                            "EmailAddress": "TestEmail2"
                        }
                    ]
                },
                {
                    "Subject": "TestSubject3",
                    "Body": "TestBody3",
                    "PreferredLanguage": "en-US",
                    "Recipients": [
                        {
                            "FirstName": "TestName3",
                            "EmailAddress": "TestEmail3"
                        }
                    ]
                }
            ]

Here is how I am attempting to do it. 这是我尝试执行的操作。

         for(var i = 0; i < requests.length; i++){
                request.post(
                    {
                        url: 'https://testURL.com/messages',
                        json: requests[i],
                        method: 'POST'
                    },
                    function (e, r, body) {
                        console.log(body);
                    }
                )
            }

I have a feeling this is a very bad way of approaching this problem. 我觉得这是解决此问题的非常不好的方法。 What is the correct way to do this? 正确的方法是什么?

You can do it that way. 你可以那样做。 Generally speaking, you want to avoid making tons of HTTP calls, so if you have the ability to edit the API you are making the requests to, you could change the endpoint to take an array (your current requests array) and return whatever you need all in one HTTP request. 一般来说,您希望避免进行大量的HTTP调用,因此,如果您能够编辑向其发出请求的API,则可以将端点更改为采用一个数组(您当前的requests数组)并返回所需的任何内容所有这些都在一个HTTP请求中。

You should not blindly make hundreds of parallel requests to a server. 您不应盲目地向服务器发出数百个并行请求。

You should have some limit on number of parallel request to a server other wise server might get down or server might block you as well 您应该限制对服务器的并行请求数,否则服务器可能会关闭或服务器也可能阻止您

I personally use eachLimit function of node's async module in these type of situations. 在这种情况下,我个人使用了节点async模块的eachLimit函数。

Following is a working code 以下是工作代码

const async = require('async');
const request = require('request');
var limit = 2 //max 2 parallel request at time

var requests = [
    {
        "Subject": "TestSubject1",
        "Body": "TestBody1",
        "PreferredLanguage": "en-US",
        "Recipients": [
            {
                "FirstName": "TestName1",
                "EmailAddress": "TestEmail1"
            }
        ]
    },
    {
        "Subject": "TestSubject2",
        "Body": "TestBody2",
        "PreferredLanguage": "en-US",
        "Recipients": [
            {
                "FirstName": "TestName2",
                "EmailAddress": "TestEmail2"
            }
        ]
    },
    {
        "Subject": "TestSubject3",
        "Body": "TestBody3",
        "PreferredLanguage": "en-US",
        "Recipients": [
            {
                "FirstName": "TestName3",
                "EmailAddress": "TestEmail3"
            }
        ]
    }
]

function iteratee(requestBody, cb) {
//this will be called for each item in the requests array
    console.log("request processing starts")
    request.post({
            url: 'https://testURL.com/messages',
            json: requestBody,
            method: 'POST'
        },
        function (e, r, body) {
            console.log(e);
            console.log(body);
            cb();
            console.log("request processing ends")
        });
}

function finalCallback(err) {
    //this will be called when all the requests are processed
}

async.eachLimit(requests, limit, iteratee, finalCallback)

All depends on your intentions: 一切取决于您的意图:

You're fine if you need to process requests' results separately (all requests are asynchronous and will be handled by passed callback function separately). 如果您需要分别处理请求的结果 (所有请求都是异步的,并将分别由传递的回调函数处理),则可以。

But often you need to make final action when all of our requests have completed . 但是, 当我们所有的请求都完成后,您通常需要采取最后的行动 You can use Promise.all for this. 您可以为此使用Promise.all

For example: 例如:

require("request/package.json"); // request is a peer dependency.
const requestPromiseAny = require("request-promise-any");

const requests = [
  {
    "name": "morpheus",
    "job": "leader"
  },
  {
    "name": "tom",
    "job": "leader"
  }
];
Promise.all(requests.map((requestJSON) => {
  return requestPromiseAny.post(
    {
      url: 'https://reqres.in/api/users',
      json: requestJSON,
      method: 'POST'
    });
})).then((responses) => {
  console.log(responses);
});

You can easily try it on runkit . 您可以在runkit上轻松尝试它。

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

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