MST

星途 面试题库

面试题:Node.js 网络通信中如何设置超时控制

在Node.js的网络通信场景下,比如使用`http`模块发起请求,描述一下如何设置超时时间,并且说明超时后如何处理相关的错误?
45.1万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试

在Node.js中使用http模块发起请求时,可以通过以下方式设置超时时间并处理超时错误:

  1. 设置超时时间: 在使用http.requesthttp.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();
    
  2. 处理超时错误: 当请求超时时,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错误码会被捕获,从而可以区分是超时错误还是其他类型的错误,并进行相应的处理。