node.js http:创建与主机的持久连接并向多个路径发送请求

时间:2016-07-27 08:45:15

标签: node.js http

我想创建持久的http连接到主机(api.development.push.apple.com)并发送许多路径的POST请求 (例如,' / 3 / device / 1',' / 3 / device / 2'等)。下面的代码是否会为每个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 个答案:

答案 0 :(得分:5)

您想要的是对所有请求使用相同的代理

如果您未在选项对象中指定代理,http模块将使用 globalAgent ,默认情况下将keepAlive设置为false。

因此,创建代理,并将其用于所有请求:

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