return a json response from a http server in typescript

You can use the built-in http module in Node.js to create an HTTP server and return a JSON response using Typescript. Here's an example:

index.ts
import http from 'http';

const server = http.createServer((req, res) => {
  const data = { message: 'Hello World!' };
  const jsonData = JSON.stringify(data);

  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Content-Length', Buffer.byteLength(jsonData));
  res.write(jsonData);
  res.end();
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});
421 chars
17 lines

In this example, we create an HTTP server using http.createServer. We set the response headers to indicate that we're returning JSON, and we write the JSON data to the response object using res.write and res.end.

You can customize the JSON data to be returned as per your requirements. By setting the Content-Type response header to application/json, the client receiving the response will know that the data being returned is in JSON format.

gistlibby LogSnag