Skip to content

"cant set headers after they are sent" occured in 2.23.2 but not in 2.21.0  #1481

@jiadi0801

Description

@jiadi0801

I use browser-sync as the server in my project since v2.18.13. Yesterday, I reinstalled my project. When I run it, the cli print:

_http_outgoing.js:494
    throw new Error('Can\'t set headers after they are sent.');

env

  • Browsersync [ 2.23.2 and 2.21.0 ]
  • Node [ 8.9.3 ]
  • windows 7
  • Git Bash

test case

// const browserSync = require('../bs/node_modules/browser-sync/');   // for bs 2.23.2
const browserSync = require('../bs21/node_modules/browser-sync/');  // for bs 2.21.0

let bs = browserSync.create('bsServer');
bs.init({
	server: '',
    open: true,
    middleware: [mw]
});
function mw(request, response, next) {
    response.write('bs');
    response.end();
    next(); 
}

when use v2.23.2, the server will stop, and throw the error below.
v2.21.0 works fine.

_http_outgoing.js:494
    throw new Error('Can\'t set headers after they are sent.');
    ^

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:494:11)
    at ServerResponse.setHeader (_http_outgoing.js:501:3)
    at D:\TMP\bs\node_modules\serve-index\index.js:213:13
    at D:\TMP\bs\node_modules\serve-index\index.js:324:7
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)

I cannot call response.end or response.write method in my middleware.
If I have to call these methods, I have to remove the next() method. This seems to prevent the middleware flow.

I want to know how this problem arises, thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions