Reputation: 1013
My code below gives me an error: Error: Can't set headers after they are sent. If I put app.use('/special/... before app.use('/' ... it doesn't give me an error- 1. As I understand when using app.use the order does matter because the program doesn't look like when I use app.get for example, for anything after '/ or '/special/ so why am I getting an error? Also when I put app.use('/special/' first I am still not seeing "first" and second" but only the first one - even though I use next.. Can someone explain? Thanks!!
What does it mean?
var express=require ('express');
var app=express();
app.use('/',function(req,res,next){
res.send('first');
next();
});
app.use('/special/',function(req,res,next){
res.send('second');
next();
});
app.listen(3000, function(){
console.log('Server listening');
});
Upvotes: 0
Views: 1361
Reputation: 1193
The two routes
app.use('/',function(req,res,next){
res.send('first');
next();
});
app.use('/special/',function(req,res,next){
res.send('second');
next();
});
both match the url /special
. That's why both of them are executed by node. Since res.send()
in the first route closes the http response from the server, the res.send()
in the second router throws an error since it tries to set a header (e. g. Content-length) while output from the first route has already been sent.
Always put the more specific route first so that it is reached at all. If the first route you define matches /
, no other route would ever be called.
Also, do not call next() if you want to call res.send() in routes. Best practice: next() should only be invoked in middlewares which do not send a response.
A possible solution looks like this:
var express=require ('express');
var app=express();
app.use('/special/',function(req,res){
res.send('second');
});
app.use('/',function(req,res){
res.send('first');
});
app.listen(3000, function(){
console.log('Server listening');
});
Upvotes: 1
Reputation: 1018
In your case it's nothing about order, but you can't invoke res.send('some_result') twice when one resource required,you can check this in detail Stackoverflow.
also, when you use app.use() to add middleware to your system,Express use regex to match your request url,so when you have the code below:
app.use('/',function(req,res,next){
res.send('first');
next();
});
all the request(regardless of HTTP verb) start with '/' will meet the requirement.
finally when request below:
POST /special
both of the middlewares will be invoked.
Upvotes: 1