等待响应2分钟后的ajax net :: ERR_EMPTY_RESPONSE - node.js服务器

问题描述 投票:4回答:2

我有这样的代码,客户端通过AJAX POST请求将文件上传到服务器,然后服务器将该文件上传到云(cloudinary),并在上传完成后响应AJAX请求。

当文件上载时间超过2分钟时(我从请求开始直到错误发生时,我计时),会出现问题。

如果上传时间不到2分钟,一切工作正常,并且错误完成后,上传时间超过2分钟没有问题。但是客户在2分钟时收到空响应。

服务器端代码:

router.route('/posts').post(middleware.isLoggedIn, function (req, res) {
  var form = new multiparty.Form()
  form.parse(req, function (err, fields, files) {
    if (err) return err
    cloudinary.v2.uploader.upload(files.content[0].path, { resource_type: 
    'auto' }, function (err, result) {
      if (err) return err
      console.log(result)
      res.json({ result: result })
    })
})

客户端代码:

function newPost (type, title, content) {
  if (type === 'image') {
    $('#newImageForm').addClass('loading')
  } else if (type === 'video') {
    $('#newVideoForm').addClass('loading')
  } else if (type === 'gif') {
    $('#newGifForm').addClass('loading')
  }
  var form = new FormData()
  form.append('content', content)
  form.append('type', type)
  form.append('title', title)
  $.ajax({
    type: 'POST',
    url: '/posts',
    data: form,
    processData: false,
    contentType: false,
    timeout: 0,
    success: function (response) {
      if (type === 'image') {
        $('#newImageForm').removeClass('loading')
        $('#newImageForm').fadeOut()
        $('#imageTitle').val('')
        $('#image').val('')
      } else if (type === 'video') {
        $('#newVideoForm').removeClass('loading')
        $('#videoTitle').val('')
        $('#video').val('')
        $('#newVideoForm').fadeOut()
      } else if (type === 'gif') {
        $('#newGifForm').removeClass('loading')
        $('#gifTitle').val('')
        $('#gif').val('')
        $('#newGifForm').fadeOut()
      }
      successMessage(response._id)
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      errorMessage()
    }
  })
}
javascript jquery node.js ajax httpresponse
2个回答
3
投票

听起来你遇到了nodejs请求的内部超时。 https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback

尝试使用req.setTimeout(10000);将其设置为更高的值或使用req.setTimeout(0)禁用它


0
投票

当您从Ajax发送需要很长时间的请求时,您必须做两件事......

首先,您需要做的是在您的ajax请求中添加超时,如下所示:

 $.ajax({
                    url: "YOUR URL",
                    type: 'POST',
                    data: { path: JSON.stringify(p) },
                    dataType: 'json',
                    timeout: 1000000,
})

但是,如果您的侦听服务器没有侦听长请求,那么这一点就不起作用,所以在节点中您执行以下操作

var server = app.listen(PORT, function() {

});

server.timeout = 600000; 

这600000是10分钟,你可以提供更长的价值,如果需要...

我希望这能解决你的问题....

© www.soinside.com 2019 - 2024. All rights reserved.