M.Sallam M.Sallam - 2 months ago 8
Javascript Question

ajax net::ERR_EMPTY_RESPONSE after waiting for response for 2 mins - node.js server

I have this code where the client uploads a file to the server through an AJAX POST request and then the server uploads that file to a cloud (cloudinary), and responds to the AJAX request after the upload is completed.

The problem occurs when the file upload takes longer than 2 minutes ( i timed it, since the beginning of the request till the error occurs).

Everything is working fine if the upload takes less than 2 minutes, And uploads that take longer than 2 minutes are completed after the error with no problem. but the client receives the empty response at the 2 minute mark.

server-side code:

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 })
})
})


Client-side code:

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()
}
})
}

Answer Source

Sounds like you are running into the internal timeout of nodejs request. https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback

Try setting it to something higher with req.setTimeout(10000); or disable it with req.setTimeout(0)