面试题答案
一键面试- 网络连接错误:
- 原因:如目标服务器不可达、网络中断等。
- 在Node.js中使用
http
模块发起请求时,若网络连接失败,http.request
的回调函数会收到一个error
参数。可以在回调函数中捕获,也可以用try - catch
块捕获。例如:
const http = require('http'); try { const req = http.request({ host: 'nonexistent-server.com', port: 80, method: 'GET' }, (res) => { // 处理响应 }); req.end(); } catch (error) { console.error('捕获到网络连接错误:', error.message); }
- 超时错误:
- 原因:请求在规定时间内未得到响应。
- 可以通过设置
timeout
选项,并结合try - catch
块捕获。示例如下:
const http = require('http'); try { const req = http.request({ host: 'example.com', port: 80, method: 'GET', timeout: 2000 // 设置2秒超时 }, (res) => { // 处理响应 }); req.on('timeout', () => { req.abort(); throw new Error('请求超时'); }); req.end(); } catch (error) { console.error('捕获到超时错误:', error.message); }
- 请求格式错误:
- 原因:如错误的HTTP方法、不正确的请求头格式等。
- 同样可以在
http.request
的回调函数中捕获错误,也可以利用try - catch
块。例如:
const http = require('http'); try { const req = http.request({ host: 'example.com', port: 80, method: 'INVALIDMETHOD' // 错误的HTTP方法 }, (res) => { // 处理响应 }); req.end(); } catch (error) { console.error('捕获到请求格式错误:', error.message); }