node.js http: create persistent connection to host and sending request to several paths

寵の児 提交于 2021-02-04 18:39:25

问题


I would like to create persistent http connection to host (api.development.push.apple.com) and send POST requests for many paths (for example, '/3/device/1', '/3/device/2', etc.). Will code below create one connection with host or many connections for each http.request()?

var http = require('http');

http.request({
    host: 'api.development.push.apple.com',
    port: 443,
    path: '/3/device/1',
    method: 'POST',
}).end();

http.request({
    host: 'api.development.push.apple.com',
    port: 443,
    path: '/3/device/2',
    method: 'POST'
}).end();

回答1:


What you want is to use the same Agent for all of your requests.

If you don't specify an agent in the options object, the http module will use the globalAgent, which sets keepAlive to false by default.

So, create your agent, and use it for all requests:

var http = require('http');
var agent = new http.Agent({ keepAlive: true }); // false by default

http.request({
    host: 'api.development.push.apple.com',
    port: 443,
    path: '/3/device/1',
    method: 'POST',
    agent: agent, // use this agent for more requests as needed
}).end();


来源:https://stackoverflow.com/questions/38608038/node-js-http-create-persistent-connection-to-host-and-sending-request-to-severa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!