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

To return a JSON response from an HTTP server with a specific status code in JavaScript when using Node.js can be achieved in multiple ways. Here's one example using the built-in http module:

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

const PORT = 3000;

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

  res.writeHead(200, {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*'
  });

  res.end(jsonResponse);
});

server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
383 chars
17 lines

In this example, we're creating an HTTP server that listens on port 3000. When the server receives a request, we create a JSON response with a message "Hello, World!" and set the response headers to indicate that the response is in JSON format.

We set the HTTP status code to 200, which indicates a successful response. If we wanted to set a different status code, such as a 404 error, we would replace the 200 parameter in res.writeHead() method with the desired status code.

Once the response headers are set, we call res.end() method to send the response to the client.

Note: The Access-Control-Allow-Origin header is added in the response code to allow requests to be made from any origin.

gistlibby LogSnag