en see
en see

Reputation: 303

ExpressJS | app.get() seem to be not working when placed below app.use() definition

From the below code, getting into '/dig' resulted to the expected response. But '/dev' doesn't work and instead return the default response defined from app.use(). However, I figured out that when I placed the app.get('/dev' .. . .) definition on top of app.use() it will work. I'm not sure why

app.get('/dig',(req,res,next)=>{
    res.end('Sending DIG');
});

app.use((req,res,next) =>{
        console.log("testing 123:");
        res.statusCode = 200;
        res.setHeader('Content-Type','text/html');
        res.end('<html><title>Express</title><head>Express App response</head><body><p>Hello, Express</p></body></html>');
    });

app.get('/dev',(req,res,next)=>{
    res.statusCode = 201;
    res.send('<html><title></title><head></head><body><p>DEV</p></body></html>');
});

//This will work

app.get('/dig',(req,res,next)=>{
    res.end('Sending DIG');
});

app.get('/dev',(req,res,next)=>{
    res.statusCode = 201;
    res.send('<html><title></title><head></head><body><p>DEV</p></body></html>');
});
app.use((req,res,next) =>{
        console.log("testing 123:");
        res.statusCode = 200;
        res.setHeader('Content-Type','text/html');
        res.end('<html><title>Express</title><head>Express App response</head><body><p>Hello, Express</p></body></html>');
    });

Upvotes: 1

Views: 227

Answers (1)

Waleed Shafiq
Waleed Shafiq

Reputation: 414

app.use() runs for every request but requests flow in a order and if app.use() is first you should avoid sending a response in it because response can be sent only once in an HTTP request. if you catch the error in the first code snippet it will say that : cannot send response headers after sending it to the client. if you need to use app.use() before then avoid sending response and use the next() function in the middle-ware so that any other app.get() or app.post() is there ,it will be called next.

app.get('/dig',(req,res,next)=>{
res.end('Sending DIG');
});

app.use((req,res,next) =>{
    console.log("testing 123:");
    next();
   });

app.get('/dev',(req,res,next)=>{
res.statusCode = 201;
res.send('<html><title></title><head></head><body><p>DEV</p></body></html>');
});

Hope this helps. GOOD LUCK :)

Upvotes: 2

Related Questions