📜  Node.js http.ClientRequest.setTimeout() 方法

📅  最后修改于: 2022-05-13 01:56:55.500000             🧑  作者: Mango

Node.js http.ClientRequest.setTimeout() 方法

http.ClientRequest.setTimeout()是 HTTP 模块中 ClientRequest 类的内置应用程序编程接口,用于设置客户端请求的请求超时。

句法:

request.setTimeout(timeout[, callback])

参数:该方法以毫秒为单位的超时值作为参数,第二个参数是给定超时值后执行的回调函数。

返回值:此方法只返回一个回调函数以供进一步操作。

示例 1:文件名-index.js

Javascript
// Node.js program to demonstrate the 
// request.setTimeout() method
 
// Importing http module
const http = require('http');
 
// Create an HTTP server
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('okay');
});
 
// Now that server is running
server.listen(3000, '127.0.0.1', () => {
 
    // Make a request
    const options = {
        port: 3000,
        host: '127.0.0.1',
        headers: {
            'Connection': 'Upgrade',
            'Upgrade': 'websocket'
        }
    };
 
    // Getting client request
    const req = http.request(options);
 
    // Setting the timeout for the client request
    // by using host method
    req.setTimeout(3000, () => {
        console.log("timeout")
        process.exit(0)
    })
});


Javascript
// Node.js program to demonstrate the 
// request.setTimeout() method
 
// Importing http module
const http = require('http');
 
// Create an HTTP server
http.createServer((req, res) => { }).listen(3000, '127.0.0.1', () => {
 
    // Getting client request
    const req = http.request({
        port: 3000,
        host: '127.0.0.1',
    });
 
    // Setting the timeout for the client request
    // by using host method
    req.setTimeout(5000, () => {
        console.log("timeout")
        process.exit(0)
    })
});


使用以下命令运行index.js文件:

node index.js

输出:

timeout

示例 2:文件名-index.js

Javascript

// Node.js program to demonstrate the 
// request.setTimeout() method
 
// Importing http module
const http = require('http');
 
// Create an HTTP server
http.createServer((req, res) => { }).listen(3000, '127.0.0.1', () => {
 
    // Getting client request
    const req = http.request({
        port: 3000,
        host: '127.0.0.1',
    });
 
    // Setting the timeout for the client request
    // by using host method
    req.setTimeout(5000, () => {
        console.log("timeout")
        process.exit(0)
    })
});

使用以下命令运行index.js文件:

node index.js

输出:

timeout

参考:https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_settimeout_timeout_callback