To create an HTTP server in Node.js, we use the built-in http
module. Here's an example of creating an HTTP server that listens on port 3000:
index.tsx200 chars10 lines
To read the request body as JSON, we need to handle the data
and end
events on the req
object. Here's a complete example that parses JSON, logs it to the console, and returns a simple response:
index.tsx737 chars30 lines
This example handles only POST requests to the /api
endpoint, and assumes that the request body is a valid JSON string. The response body simply returns a JSON object with a status
property set to 'success'
. If the request body can't be parsed as JSON, the server returns a 400 status code and an error message.
This is just a basic example, but it should give you a starting point for creating an HTTP server with JSON parsing and response.
gistlibby LogSnag