To return a JSON response with a specific status code from an HTTP server in Typescript, you can use the response
object provided by the express framework. Here is an example:
index.ts387 chars21 lines
In the example above, we define a GET route at /users
that returns an array of users. If the array is not empty, we respond with a 200 OK
status code and the users in JSON format. If there are no users, we respond with a 404 Not Found
status code and a JSON object with an error message.
The res.status
method is used to set the HTTP status code and the res.json
method is used to convert the response object to JSON format and send it back to the client.
gistlibby LogSnag