Proper way to set response status and JSON content in a REST API made with nodejs and express

前端 未结 12 705
无人及你
无人及你 2020-11-30 20:25

I am playing around with Nodejs and express by building a small rest API. My question is, what is the good practice/best way to set the code status, as well as the response

相关标签:
12条回答
  • 2020-11-30 20:27

    You could do this

                return res.status(201).json({
                    statusCode: req.statusCode,
                    method: req.method,
                    message: 'Question has been added'
                });
    
    0 讨论(0)
  • 2020-11-30 20:29
    res.status(500).jsonp(dataRes);
    
    0 讨论(0)
  • 2020-11-30 20:39

    res.sendStatus(status) has been added as of version 4.9.0

    you can use one of these res.sendStatus() || res.status() methods

    below is difference in between res.sendStatus() || res.status()

    
    res.sendStatus(200) // equivalent to res.status(200).send('OK')
    res.sendStatus(403) // equivalent to res.status(403).send('Forbidden')
    res.sendStatus(404) // equivalent to res.status(404).send('Not Found')
    res.sendStatus(500) // equivalent to res.status(500).send('Internal Server Error')
    
    

    I hope someone finds this helpful thanks

    0 讨论(0)
  • 2020-11-30 20:41

    A list of HTTP Status Codes

    The good-practice regarding status response is to, predictably, send the proper HTTP status code depending on the error (4xx for client errors, 5xx for server errors), regarding the actual JSON response there's no "bible" but a good idea could be to send (again) the status and data as 2 different properties of the root object in a successful response (this way you are giving the client the chance to capture the status from the HTTP headers and the payload itself) and a 3rd property explaining the error in a human-understandable way in the case of an error.

    Stripe's API behaves similarly in the real world.

    i.e.

    OK

    200, {status: 200, data: [...]}
    

    Error

    400, {status: 400, data: null, message: "You must send foo and bar to baz..."}
    
    0 讨论(0)
  • 2020-11-30 20:42

    Express API reference covers this case.

    See status and send.

    In short, you just have to call the status method before calling json or send:

    res.status(500).send({ error: "boo:(" });
    
    0 讨论(0)
  • 2020-11-30 20:45

    I am using this in my Express.js application:

    app.get('/', function (req, res) {
        res.status(200).json({
            message: 'Welcome to the project-name api'
        });
    });
    
    0 讨论(0)
提交回复
热议问题