How do I handle different routes with the http module?
Check request.url and request.method in the listener. If url is '/api/users' and method is 'GET', send the users. This is manual routing, which Express makes easier, but it teaches how servers work.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in How to Create an HTTP Server in Node.js From Scratch
Import the http module with require('http'), call http.createServer with a request listener function, and listen on a port with server.listen(port). The listener receives request and response objects.
A function that receives request and response. The request has the URL, method, and headers. The response is what you send back: status code, headers, and body via writeHead and end.
Call response.writeHead(200, { 'Content-Type': 'application/json' }), then response.end(JSON.stringify(data)). Set the Content-Type to application/json and send a JSON string.
Still have questions?
Browse all our FAQs or reach out to our support team
