Nodejs: fixed the "Can't remove headers after they are sent" exception caused by the cancellation of res. download of express.

Source: Internet
Author: User
Document directory
  • Love
From Baidu?

Presumably, you may have encountered the same problem as me.

In express, if we use res. download to process file downloads and the download is canceled midway through, the following exception will occur:

node.js:116    throw e; // process.nextTick error, or 'error' event on first tick        ^        Error: Can't remove headers after they are sent.        at ServerResponse.removeHeader (http.js:537:11)        at Socket. (/usr/local/lib/node/.npm/express/2.0.0rc/package/lib/response.js:205:19)        at Socket.emit (events.js:59:20)        at Array. (net.js:799:27)        at EventEmitter._tickCallback (node.js:108:2

I checked the source code of express and found that the "Content-Disposition" http header will be removed when err occurs. This will cause exceptions because the response has been sent to the client, we only need to set the "if (err) self. removeHeader ('content-disposition'); "comment out the source code.
If you do not want to modify the source code of express, we can perform a simple fix on express after require ('express:

var express = require('express');//fixed express download cancel bug:require('http').ServerResponse.prototype.download = function(path, filename, fn){    var self = this;    // support callback as second arg     if ('function' == typeof filename) {        fn = filename;        filename = null;    }    // transfer the file     this.attachment(filename || path).sendfile(path, function(err){        // if (err) self.removeHeader('Content-Disposition');         if (fn) return fn(err);        if (err) {            self.req.next('ENOENT' == err.code                ? null                : err);        }    });};
Love

^_^. I hope this article will be useful to you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.