您好,欢迎访问一九零五行业门户网

在 Node.js 中创建代理

您可以使用 new agent() 方法在 node.js 中创建代理实例。 http.request() 方法使用“http”模块中的 globalagent 创建自定义 http.agent 实例。
语法new agent({options})
参数上述函数可以接受以下参数−
选项 – 这些选项将包含创建时可以在代理上设置的可配置选项。以下是代理可以拥有的字段/选项 -
keepalive  - 此方法保持套接字是否有任何未完成的请求或不,但保留它们以供将来的任何请求使用,而无需实际重新建立 tcp 连接。可以使用“关闭连接”来关闭此连接。默认值: false。
keepalivemsecs - 将 keepalive 选项设置为 true 时,此选项定义 tcp keep-alive 数据包的初始延迟。默认值为 1000。
ma​​xsockets - 此选项定义每个主机允许的最大套接字数。默认情况下,该值为无穷大。
ma​​xtotalsockets – 所有主机允许的套接字总数。每个请求都使用一个新的套接字,直到达到限制。默认值为无穷大。
ma​​xfreesockets - 这是在空闲状态下可以保持打开状态的空闲套接字的最大数量。默认值为:256。
调度 - 这是在选择下一个要使用的空闲套接字时可以应用的调度策略。调度可以是“fifo”或“lifo”。
超时 - 表示套接字超时(以毫秒为单位)。
示例创建一个名为agent.js的文件并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示 -
node agent.js
agent.js
 现场演示
// node.js program to demonstrate the creation of new agent// importing the http moduleconst http = require('http');// creating a new agentvar agent = new http.agent({});// defining options for agentconst aliveagent = new http.agent({ keepalive: true, maxsockets: 5,});// creating connection with alive agentvar aliveconnection = aliveagent.createconnection;// creating new connectionvar connection = agent.createconnection;// printing the connectionconsole.log('succesfully created connection with agent: ',connection.tostring);console.log('succesfully created connection with alive agent: ',aliveconnection.tostring);
输出c:\homeode>> node agent.jssuccesfully 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 program to demonstrate the creation of new agent// importing the http moduleconst http = require('http');// importing the agentkeepalive moduleconst agent = require('agentkeepalive');// creating a new agentconst keepaliveagent = new agent({});// implementing some optionsconst options = { host: 'tutorialspoint.com', port: 80, path: '/', method: 'get', agent: keepaliveagent,};// requesting details via http server moduleconst req = http.request(options, (res) => { // printing statuscode, headers and other details // received from the request console.log("statuscode: ", res.statuscode); console.log("headers: ", res.headers);});// printing the agent optionsconsole.log("agent options: ", req.agent.options);req.end();
输出c:\homeode>> node agent.jsagent options: { socketactivettl: 0, timeout: 30000, freesockettimeout: 15000, keepalive: true, path: null }statuscode: 403headers: { 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' }
以上就是在 node.js 中创建代理的详细内容。
其它类似信息

推荐信息