To create a HTTP server in TypeScript, we can use the built-in http
module. Here's an example of how to create a basic HTTP server and parse the request body:
index.ts1037 chars35 lines
In this example, we create an HTTP server using the createServer
method from the http
module. We handle POST requests by listening to the data
and end
events of the request object. The request body is stored in the body
variable and parsed as JSON using the JSON.parse
method. If an error occurs during parsing, a 400 Bad Request
response is sent. If parsing is successful, a 200 OK
response is sent with a JSON message.
For all other HTTP methods, a 405 Method Not Allowed
response is sent.
Note that this example only parses JSON request bodies. For other types of request bodies, you may need to use a different parsing method.
gistlibby LogSnag