【问题标题】:Node js request timeout issueNode js请求超时问题
【发布时间】:2019-09-08 16:07:39
【问题描述】:

我的应用程序正在响应并通过axios 调用调用node 层。然后node 层调用外部api,这需要大约 7 分钟的响应时间。但是,我在发出请求后大约 2-3 分钟内收到超时错误。当我直接调用外部 api(而不是通过节点层)时,我能够在 7 分钟内得到响应。我尝试使用类似的建议为node 设置timeout

var http = require('http');
    http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end("Hello World");
    }).on('connection', function(socket) {
      socket.setTimeout(200000000);
    }).listen(3000);

并且还使用 server.timeout 但似乎没有任何效果。有人可以建议如何解决这个问题。

我收到以下错误

createError 处的网络错误 (webpack-internal:///./node_modules/axios/lib/core/createError.js:16:15

我正在使用 axios

axios.post('/api/parseAndExtractFile', formData, config)
  .then((response) => {
    if (response.status === 200) {
      const fileName = `enriched_v3_spec_${new Date().getTime()}`
      const blob = new Blob([(response.data)], {type: 'application/vnd.ms-excel.sheet.macroEnabled.12'})
      saveAs(blob, fileName)
    } else {
      toast.error('Oops, something went wrong. Please try again.', {autoClose: 4000})
    }
    this.setState({
      loading: false,
      showAuditLog: 'show'
    })
  })
  .catch((error) => {
    this.setState({loading: false})
    toast.error(`Error while fetching data ${error}`, {autoClose: 4000})
  })

【问题讨论】:

  • 超时以毫秒为单位,所以10000 只是 10 秒,尝试像 420000 一样增加(7 分钟)stackoverflow.com/questions/23925284/…
  • 我已经尝试将超时设置为 200000000000。它不起作用。

标签: node.js reactjs timeout axios connection-timeout


【解决方案1】:

node和axios都有超时

1) 设置节点超时时间

var http = require('http');
var srvr = http.createServer(function (req, res) {
  res.write('Hello World!');
  res.end();
});
srvr.listen(8080);
srvr.timeout = 20000; // in milliseconds

2) 为 axios 设置超时时间

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 10000, // in milliseconds
  headers: {'X-Custom-Header': 'foobar'}
});

【讨论】:

    【解决方案2】:

    我认为您在错误的地方调用 setTimeOut。您可能需要在 var 中设置 createServer,然后对其调用 setTimeOut,如下所示:

    `var http = require('http');
    var srv = http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end("Hello World");
    })
    
    svr.listen(3000);
    svr.setTimeout(10000);
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多