When writing a RESTful API in Node.js, defining the return value of a controller action by returning a status code, response object, and optional message can improve the ease of use of the API and correct processing by the client.
How to write Node.js interface return value
When writing RESTful API in Node.js, for control It is important to define the return value of the operator operation. Correct return values not only improve the usability of the API, but also help clients handle requests correctly.
Determine the response status code
First, determine the HTTP status code to be returned. The following are some common status codes:
Create response object
Next, Create a JavaScript object to represent the response. This object typically includes the following properties:
<code>{ status: <HTTP 状态码>, data: <响应数据>, message: <可选消息> }</code>
Set HTTP status code
Assign the HTTP status code to the status
property.
Set response data
Assign response data to the data
attribute. Data can be any JavaScript value, such as a string, object, or array.
Set optional message
If desired, a message can be assigned to the message
property. The message provides additional information about the response.
Example
The following is an example of a successful response:
<code class="javascript">res.status(200).json({ data: { name: "John Doe", age: 30 } });</code>
The following is an example of an error response:
<code class="javascript">res.status(400).json({ message: "Invalid request format" });</code>
Passed By following these steps, you can write clear and informative Node.js interface return values, improving the overall experience of your API.
The above is the detailed content of How to write interface return value in nodejs. For more information, please follow other related articles on the PHP Chinese website!