How to create a HTTP server in Node.js

Ckmobile
3 min readJan 4, 2021

--

In this article, we are going to create a server that listens for requests from the browser and then decides what responses to send to the browser .

Complete Node.js articles:

Part 1: How to create a HTTP server in Node.js

Part 2: How To Use the `req` Object in in Node.js

Part 3: How To Use the `res` Object in in Node.js

Part 4: How to render HTML in Node.js

Part 5: Node.js routing without using Express.js

Part 6: How to specify statusCode in Node.js

Part 7: How to redirect user’s browser URL to a different page in Nodejs?

Part 8: How to download and install a npm package globally in Node.js?

Part 9: What is package.json and how to install a npm package locally in Node.js?

Full course:

const http = require('http');

First, create server.js and then require the core module, which is http module.

const server = http.createServer((req, res) => {console.log('A request is made')});

To create the server, we can use http.createServer() method. We can store the instance of the server to the constant server. There is a callback function, this function will run every time a request come to the server.

This function takes a request object and a response object as parameters.

The request object contains things such as the requested URL, but in this example we ignore it and always return “A request is made”.

The response object is to send the response to the user in the browser

const http = require('http');const hostname = 'localhost';const port = 3000;const server = http.createServer((req, res) => {console.log('A request is made')});server.listen(port,hostname, () => {console.log(`listening on port ${port}`)})

To actively listening for the requests being sent to the server, we need to invoke the listen method.

We need to pass in the argument like port number, hostname, the default value of the second argument is “localhost”, so we can also skip this.

server.listen(port, () => {console.log(`listening on port ${port}`)})

Now, the most basic server is created. When we run “node server”, the process is ongoing, this is because the server is running in the background and listening for the requests. To cancel the process, we need to press Ctrl + C.

listening for the requests

If the run the server again, and go to the browser and make a request by typing http://localhost:3000.

The browser is hang and waiting for the server response, but we did not create any response yet. However, we see “A request is made” is logged to the console.

Subscribe Youtube:

Follow us:

--

--

Ckmobile
Ckmobile

Written by Ckmobile

Teaching JavasScript, React, React Native, MongoDB and NodeJS https://linktr.ee/ckmobile

No responses yet