return a json response from a http server with a specific status code in typescript

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.ts
import express from 'express';

const app = express();

app.get('/users', (req, res) => {
  const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
  ];
  
  if (users.length > 0) {
    res.status(200).json(users);
  } else {
    res.status(404).json({ message: 'No users found' });
  }
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
387 chars
21 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