nunjucks: Error: Can't set headers after they are sent. (Express 4)
I am getting this when using with express 4 and express-flash.
I used with swig and all worked.
Here is failing when render is called, it return the html and then fails.
Wed, 27 Jan 2016 21:41:57 GMT connect:redis GET "5cg6LbHdXhWuUnKXYWL6kPNRfeN1TN9u"
Wed, 27 Jan 2016 21:41:57 GMT connect:redis SET "yWgxdkWw0rTHBpi-RuzqRkYLbOUQGdYG" {"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"flash":{}} ttl:86400
_http_outgoing.js:335
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (/Users/carlitux/Projects/project/node_modules/express/lib/response.js:718:10)
at ServerResponse.send (/Users/carlitux/Projects/project/node_modules/express/lib/response.js:163:12)
at done (/Users/carlitux/Projects/project/node_modules/express/lib/response.js:957:10)
at /Users/carlitux/Projects/project/node_modules/nunjucks/src/environment.js:22:23
at RawTask.call (/Users/carlitux/Projects/project/node_modules/asap/asap.js:40:19)
at flush (/Users/carlitux/Projects/project/node_modules/asap/raw.js:50:29)
at doNTCallback0 (node.js:419:9)
at process._tickCallback (node.js:348:13)
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 18 (1 by maintainers)
I don’t use Express, so I probably won’t be able to be much help here. Usually that kind of error is because something is sending output to the client earlier than expected? I don’t have any idea why Nunjucks would be different from Swig in that regard, though.
because you might send no less than 2 times response.
like my code:
I used
Promise.then()
and my functionnext()
goes before myres.send()
, so I had response more than 1 times to front-end. like me, you can write like this.@carljm looks like that is the issue if I use
Instead of
All works fine. looks like asap lib and /Users/carlitux/Projects/project/node_modules/nunjucks/src/environment.js:22:23 are calling the callback before what is expected.
Happened with me while I was sending response twice and not using return with one of them.
Here when user is not found res.send() is called twice so using return fixed this error.
So you can check if res.send() is not called twice as this is one case of getting this error.
I have this problem too. When refresh twice quickly. Then happened Any solution?
nevermind express-flash just tested with simple middleware:
and it is failing.
^This is a bug I feel anyone using express would run into. I too have the same issue.
If you have the template render after passing through middleware and the page is refreshed too quickly. The page errors and the app errors.
If you add this code to your project probably works …