I have an upload function which uploads a file. There is also an abort function to abort the request.
upload(){
this.req = $.ajax(SetupService.baseUrl + '/upload/audio', {
xhr: () => {
const xhr = new XMLHttpRequest()
return xhr;
},
processData: false,
contentType: false,
data: formdata
});
}
abort() {
this.req.abort();
}
In the serve side i use nodej with express and multer for file handling. The file uploading works successfully but if I click abort button, the server doesn't know. How to check from express js server if the request is aborted or not
router.post('/audio', function (req, res) {
console.log('uploading');
// How to check if the req is aborted by client or not
});
I wanted to supplement Gershom's answer with some more details and code examples.
Unfortunately, node has deprecated the abort event and the aborted property on the IncomingMessage class. I'm not sure why they did this, but I generally trust their decisions, as inconvenient as they can be sometimes.
I would assume that the best way to see if a request was interrupted is to do a combination of the following:
Check if the request is "complete" when it closes:
req.on('close', () => {
if (!req.complete) {
// it got interrupted somehow - it could have been aborted, or maybe
// they lost internet, or a firewall cut it off... you don't really know
}
});
Listen for the socket close event on the underlying net.Socket instance:
req.socket.on('close', (hadError) => {
// no more data can be read or written to the socket,
// but we don't really know why or how it was closed
if (hadError) {
// This will be true if the socket "had a transmission error".
// The docs are not clear on what causes a transmission error.
}
});
Other notes:
req.socket is the same as the res.socket (eg. req.socket === res.socket??). I would hope they refer to the same thing for a server request, but if not, you will want to listen for the 'close' event for both.close event for the response. It is emitted when the response is either complete or interrupted, but you can't tell which. This is why listening to the socket 'close' event is needed.The deprecated way to do this is req.on('aborted', () => { ... }). The modern equivalent is req.on('close', () => { ... }).
Note that both Requests and Responses can be aborted! A Request will abort if the connection is destroyed before the Request has been fully consumed (all headers, payload, and final \r\n sequence received). A Response will end if the connection is destroyed before the Response is sent (indicating that sending the Response will not succeed in communicating with the client).
Therefore you may also want to monitor Response abortions, via res.on('close', () => { ... }).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With