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

前端 未结 12 753
无人及你
无人及你 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: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..."}
    

提交回复
热议问题