return a json response from a http server in javascript

To return a JSON response from a HTTP server in Node.js, you can use the built-in http module and the JSON.stringify() method.

Here's an example:

index.tsx
const http = require('http');

const server = http.createServer((req, res) => {
  const data = { message: 'Hello, world!' };
  res.setHeader('Content-Type', 'application/json');
  res.end(JSON.stringify(data));
});

server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});
299 chars
12 lines

In this example, we create a server using the http.createServer() method. When a request is made to this server, we create a JSON object data, set the content type of the response to application/json, and use JSON.stringify() to convert data to a JSON string. Finally, we send the JSON string as the response using res.end().

gistlibby LogSnag