0

if error occurs in first function i.e mw1 error msg in response & response is end but, i don't want node to process that req further after sending response, but now the next function mw2 executes after sending response. which gives error cant set header. i tried next('route') but no use. please suggest how to get this done.

function mw1(req, res, next){
    if(req.id == 1){
         res.status('500');
                    res.json({
                        STATUS: "error",
                        http_code: '500',
                        msg: 'function 1',
                        error_code: ''
                    });
                    res.end();
    }

    next();

  }

function mw2(req, res, next){
    if(req.id == 2){
         res.status('500');
                    res.json({
                        STATUS: "error",
                        http_code: '500',
                        msg: 'function 2',
                        error_code: ''
                    });
                    res.end();
    }

    next();

}

function mw3(req, res, next){

    if(req.id == 3){
         res.status('500');
                    res.json({
                        STATUS: "error",
                        http_code: '500',
                        msg: 'function 3',
                        error_code: ''
                    });
                    res.end();
    }

    next();

}

app.use('/sub', mw1);
app.use('/sub', mw2);
app.use('/sub', mw3);
Arrow
  • 153
  • 1
  • 2
  • 12

1 Answers1

2

Once the response is already sent to the browser, the HTTP server cannot modify it since it is already sent to the client.

You can only send or set headers if you have not already called res.json, res.send or res.end.

Calling res.json or res.end will send the response to the browser (also sending the headers) so you cannot further change or send more headers or anything to the browser

Usama Ejaz
  • 1,105
  • 10
  • 20