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.tsx383 chars17 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