把http请求放到定时器里,执行第二次是会报错

在axios的github上也查到了类似的问题,但是这个好像不是axios的问题,node自带的http也会有。我感觉是异步的问题,stackoverflow上也有人推测说是和异步有关,解决方案是改了axios的源码

var timer=setInterval(function() {
  console.log(moment(new Date()).format('HH:mm:ss'));
  main();
}, 5000)
main
const config = {
  method: 'get',
  url: `${mymblog_url}?uid=${id}&page=1&feature=0`,
  headers: { 
    Cookie: cookie,
    // timeout:300000,
    // Connection: 'keep-alive',
    ...data.getHeaders()
  },
  httpsAgent: httpsAgent,
  data : data,
};
exports.main = async function() {
  await Axios(config).then(({data, status}) => {
    console.log('status', status);
    const weiboList = data.data.list.sort((a, b) => {
      return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
    });
    console.log(weiboList.length);
  }).catch(error => {
    console.error(error);
  });
}
F:\nodejs-demo\DEMO\test>node task.js
11:27:06
status 200
9
11:27:11
11:27:16
11:27:21
11:27:26
Error: socket hang up
    at connResetException (node:internal/errors:691:14)
    at TLSSocket.socketOnEnd (node:_http_client:471:23)
    at TLSSocket.emit (node:events:402:35)
    at endReadableNT (node:internal/streams/readable:1343:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
阅读 2k
1 个回答

并没有发现node有你说的问题

const http = require("http");
const https = require("https");

function fetch(url) {
  const { protocol, pathname, search, port, hostname } = new URL(url);
  const options = {
    path: pathname + search,
    port: port,
    method: "get",
    hostname: hostname,
  };
  const nodeImpl = protocol === "https:" ? https : http;
  return new Promise((resolve, reject) => {
    const request = nodeImpl.request(options, (res) => {
      let parts = [];
      res.on("error", reject);
      res.on("end", () => resolve(Buffer.concat(parts)));
      res.on("data", (d) => parts.push(d));
    });
    request.end();
  });
}

setInterval(() => {
  fetch("http://www.baidu.com").then(
    (buf) => {
      console.log(buf.toString().substring(0, 20));
    },
    (err) => {
      console.err(err);
    }
  );
}, 1000);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题