當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js http.ClientRequest.setTimeout()用法及代碼示例

http.ClientRequest.setTimeout()是HTTP模塊內的ClientRequest類的內置應用程序編程接口,用於為客戶端請求設置請求超時。

用法:

request.setTimeout(timeout[, callback])

參數:此方法將超時值作為參數(以毫秒為單位),第二個參數是在給定超時值之後執行的回調函數。

返回值:此方法隻返回回調函數以進行進一步操作。

範例1:Filename-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 clinet request 
    const req = http.request(options); 
  
    // Setting the timeout for the client reauest 
    // by using host method 
    req.setTimeout(3000, () => { 
        console.log("timeout") 
        process.exit(0) 
    }) 
});

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

node index.js

輸出:

timeout

示例2:Filename-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 clinet request 
    const req = http.request({ 
        port:3000, 
        host:'127.0.0.1', 
    }); 
  
    // Setting the timeout for the client reauest 
    // 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

相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Node.js http.ClientRequest.setTimeout() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。