面试题答案
一键面试在Node.js中使用http
模块发起请求时,可以通过以下方式设置超时时间并处理超时错误:
-
设置超时时间: 在使用
http.request
或http.get
创建请求对象后,可以调用请求对象的setTimeout
方法来设置超时时间(单位为毫秒)。例如:const http = require('http'); const options = { host: 'example.com', port: 80, path: '/', method: 'GET' }; const req = http.request(options, (res) => { // 处理响应 res.on('data', (chunk) => { console.log('Received:', chunk.toString()); }); res.on('end', () => { console.log('Response ended'); }); }); req.setTimeout(5000, () => { // 这里的5000表示5秒超时 req.abort(); }); req.end();
-
处理超时错误: 当请求超时时,
setTimeout
的回调函数会被触发。在这个回调函数中,可以通过调用请求对象的abort
方法来终止请求。同时,请求对象的error
事件也会被触发,在error
事件的处理函数中可以处理超时相关的错误信息。例如:const http = require('http'); const options = { host: 'example.com', port: 80, path: '/', method: 'GET' }; const req = http.request(options, (res) => { // 处理响应 res.on('data', (chunk) => { console.log('Received:', chunk.toString()); }); res.on('end', () => { console.log('Response ended'); }); }); req.setTimeout(5000, () => { req.abort(); }); req.on('error', (err) => { if (err.code === 'ECONNABORTED') { console.log('请求超时:', err.message); } else { console.log('其他错误:', err.message); } }); req.end();
在上述代码中,当请求超时时,ECONNABORTED
错误码会被捕获,从而可以区分是超时错误还是其他类型的错误,并进行相应的处理。