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

前端 未结 12 706
无人及你
无人及你 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:46

    You could do it this way:

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

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

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

    status of 200 will be the default when using res.send, res.json, etc.

    You can set the status like res.status(500).json({ error: 'something is wrong' });

    Often I'll do something like...

    router.get('/something', function(req, res, next) {
      // Some stuff here
      if(err) {
        res.status(500);
        return next(err);
      }
      // More stuff here
    });
    

    Then have my error middleware send the response, and do anything else I need to do when there is an error.

    Additionally: res.sendStatus(status) has been added as of version 4.9.0 http://expressjs.com/4x/api.html#res.sendStatus

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

    The standard way to get full HttpResponse that includes following properties

    1. body //contains your data
    2. headers
    3. ok
    4. status
    5. statusText
    6. type
    7. url

    On backend, do this

    router.post('/signup', (req, res, next) => {
        // res object have its own statusMessage property so utilize this
        res.statusText = 'Your have signed-up succesfully'
        return res.status(200).send('You are doing a great job')
    })
    

    On Frontend e.g. in Angular, just do:

    let url = `http://example.com/signup`
    this.http.post(url, { profile: data }, {
        observe: 'response' // remember to add this, you'll get pure HttpResponse
    }).subscribe(response => {
        console.log(response)
    })
    
    0 讨论(0)
  • 2020-11-30 20:48

    FOR IIS

    If you are using iisnode to run nodejs through IIS, keep in mind that IIS by default replaces any error message you send.

    This means that if you send res.status(401).json({message: "Incorrect authorization token"}) You would get back You do not have permission to view this directory or page.

    This behavior can be turned off by using adding the following code to your web.config file under <system.webServer> (source):

    <httpErrors existingResponse="PassThrough" />

    0 讨论(0)
  • 2020-11-30 20:51
    try {
      var data = {foo: "bar"};
      res.json(JSON.stringify(data));
    }
    catch (e) {
      res.status(500).json(JSON.stringify(e));
    }
    
    0 讨论(0)
  • 2020-11-30 20:52

    The best way of sending an error response would be return res.status(400).send({ message: 'An error has occurred' }).

    Then, in your frontend you can catch it using something like this:

            url: your_url,
            method: 'POST',
            headers: headers,
            data: JSON.stringify(body),
        })
            .then((res) => {
                console.log('success', res);
            })
            .catch((err) => {
                err.response && err.response.data && this.setState({ apiResponse: err.response.data })
            })
    

    Just logging err won't work, as your sent message object resides in err.response.data.

    Hope that helps!

    0 讨论(0)
提交回复
热议问题