Which is the proper way to set response status and JSON content in a REST API made with nodejs and express ?

Which is the proper way to set response status and JSON content in a REST API made with nodejs and express ?

Asked on October 24, 2018 in node.js.
Add Comment


  • 4 Answer(s)

     Before calling json or send, first we need to call the status method:

    res.status(500).send({ error: "boo:(" });
    
    Answered on October 24, 2018.
    Add Comment

    Try this:

    res.status(400).json(json_response);
    

     It will works even in express 4. Then above code will set the HTTP status code to 400

    Answered on October 24, 2018.
    Add Comment

    When using res.send, res.json, etc.
    status of 200 will become default.

    we can set the status

    res.status(500).json({ error: 'something is wrong' });
    
    router.get('/something', function(req, res, next) {
        // Some stuff here
        if(err) {
            res.status(500);
            return next(err);
        }
        // More stuff here
    });
    
    Answered on October 24, 2018.
    Add Comment
    res.status(400).json(json_response);

    This will set the HTTP status code to 400, it works even in express 4.

    Answered on February 21, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.