在 Node.js 中创建代理

您可以使用 newAgent()方法在 Node.js 中创建代理的实例。该方法使用来自“http”模块的 globalAgent 来创建自定义实例。http.request()http.Agent

语法

new Agent({options})

参数

上述函数可以接受以下参数 -

  • 选项 - 这些选项将包含可在创建时在代理上设置的可配置选项。以下是代理可以拥有的字段/选项 -

    • keepAlive  – 此方法保持套接字是否有任何未完成的请求,但为将来的任何请求保留它们,而无需实际重新建立 TCP 连接。可以使用“关闭”连接来关闭此连接。默认值:假。

    • keepAliveMsecs  – 使用 keepAlive 选项为真时,此选项定义 TCP keep-Alive 数据包的初始延迟。默认值为 1000。

    • maxSockets  – 此选项定义每个主机允许的最大套接字数。默认情况下,此值为无穷大。

    • maxTotalSockets  – 所有主机允许的套接字总数。每个请求都使用一个新的套接字,直到达到限制。默认值为无穷大。

    • maxFreeSockets  - 这是在空闲状态下可以保持打开的最大空闲套接字数。默认值为:256。

    • 调度 ——这是在选择下一个要使用的空闲套接字时可以应用的调度策略。调度可以是“fifo”或“lifo”。

    • timeout  – 以毫秒为单位表示套接字超时。

示例

创建一个具有名称的文件 -agent.js并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示 -

node agent.js

代理.js

//Node.js程序来演示创建新的Agent

// 导入http模块
const http = require('http');

// 创建新代理
var agent = new http.Agent({});

// 定义代理选项
const aliveAgent = new http.Agent({
   keepAlive: true, maxSockets: 5,
});

// 创建与活动代理的连接
var aliveConnection = aliveAgent.createConnection;

// 创建新连接
var connection = agent.createConnection;

// 打印连接
console.log('Succesfully created connection with agent: ',
connection.toString);
console.log('Succesfully created connection with alive agent: ',
aliveConnection.toString);
输出结果
C:\home\node>> node agent.js
Succesfully created connection with agent: function toString() { [native code] }
Succesfully created connection with alive agent: function toString() { [native code] }

示例

'agentkeepalive' 模块在尝试创建套接字或代理时提供了更好的灵活性。为了更好地理解,我们将在下面的例子中使用这个模块。

安装

npm install agentkeepalive --save

程序代码

//Node.js程序来演示创建新的Agent

// 导入http模块
const http = require('http');
// 导入 agentkeepalive 模块
const Agent = require('agentkeepalive');

// 创建新代理
const keepAliveAgent = new Agent({});

// 实现一些选项
const options = {
   host: 'nhooo.com',
   port: 80,
   path: '/',
   method: 'GET',
   agent: keepAliveAgent,
};

// 通过 http 服务器模块请求详细信息
const req = http.request(options, (res) => {
   // 打印状态码、标题和其他详细信息
   // 从请求中收到
   console.log("StatusCode: ", res.statusCode);
   console.log("Headers: ", res.headers);
});

// 打印代理选项
console.log("代理选项: ", req.agent.options);
req.end();
输出结果
C:\home\node>> node agent.js
代理选项: { socketActiveTTL: 0,
   timeout: 30000,
   freeSocketTimeout: 15000,
   keepAlive: true,
   path: null }
StatusCode: 403
Headers: { date: 'Sun, 25 Apr 2021 08:21:14 GMT',
   server: 'Apache',
   'x-frame-options': 'SAMEORIGIN',
   'last-modified': 'Thu, 16 Oct 2014 13:20:58 GMT',
   etag: '"1321-5058a1e728280"',
   'accept-ranges': 'bytes',
   'content-length': '4897',
   'x-xss-protection': '1; mode=block',
   vary: 'User-Agent',
   'keep-alive': 'timeout=5, max=100',
   connection: 'Keep-Alive',
   'content-type': 'text/html; charset=UTF-8' }