我有这段代码,客户端通过AJAX POST请求将文件上传到服务器,然后服务器将文件上传到云(云),并在上传完成后响应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()
    }
  })
}

最佳答案

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

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

关于javascript - 等待响应2分钟后的ajax net::ERR_EMPTY_RESPONSE-node.js服务器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45910084/

10-10 06:04