- Building Enterprise JavaScript Applications
- Daniel Li
- 254字
- 2021-07-23 16:31:10
Our HTTP server in detail
Let's break down our HTTP server code to see what's really going on. First, we require the http package so we can access the HTTP module's methods:
const http = require('http');
Next, we use the createServer method to create a server instance that listens to incoming requests. Inside it, we pass in a request handler function that takes a req and res parameters.
The req parameter is an object containing information about the request, such as its origin IP, URL, protocol, body payload (if any), and so on. The res object provides methods that help you prepare the response message to send back to the client; for example, you can set the header, add a response body, specify the content type of the body, and so on.
When we run res.end(), it finishes the preparation of the response and sends it back to the client. Here, we disregard what the request was, and it simply returns with Hello, World!:
const requestHandler = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!');
}
const server = http.createServer(requestHandler);
Now that we have created a server instance and configured its response, the last step is to give it a port and instruct it to listen for requests on that port.
server.listen(8080);