How to create a simple HTTP server?

How to create a simple HTTP server?

In this article, we will learn how to create a simple Node.js web server and handle HTTP requests.

ยท

3 min read

You need a webserver to access the web pages of any web application that will handle all the HTTP requests for the application asynchronously. Node.js makes it easy to create a web server that handles incoming requests asynchronously. A web server provides interaction between users and the application. Web servers allow you to load images and HTML web pages to users of your application. A web server receives HTTP requests from a client e.g., your browser, and provides an HTTP response like an HTML page or JSON.

Creating a Node.js web server.

The following example is a simple web server contained in the server.js file.

// Import http module
const http = require('http');

const port = 8080;
const host = 'localhost';

// Creating a server
const server = http.createServer((req, res) => {
    // handle incoming requests
    // set response header
    res.writeHead(200, { 'Content-Type': 'text/html' });

    // set response content
    res.write(`
        <html>
            <body style="background: black; color: white; text-align: center;">
                <h1>Welcome</h1>
                <p>Let's get started</p>
            </body>
        </html>
`);
    res.end();
});

// Listen for any incoming requests
server.listen(port, host, () => {
    console.log(`Server is running on http://${host}:${port}`);
});

In the above example;

  • We import the http module using the require() function which is an in-built module of Node.js, so you don't need to install using npm.

  • We define two constants: the host and the port. Localhost is a special private address that computers use to refer to themselves. A port is a number that servers use as an endpoint to our IP Address.

  • We then create a server by calling the createServer() method with a call back function that takes in request and response as parameters that are supplied by Node.js. The request object is used to get information about the current HTTP request e.g. data. The response object is used to send a response for a current HTTP request. To send a response, we set the response header using writeHead() method and set the response content or body using write() method. The server will send the response using end() method. You must end your response with end() to tell the server you are no longer writing content.

  • Finally, we call the listen() method on the server object we created earlier that was returned from the createServer() method with a port number to start listening to incoming requests. It accepts three arguments; port, host, and a call back function that fires when the server begins to listen.

You can now run the web server that you created by writing the command node server.js in the command prompt or terminal window for example;

server.PNG

Output:

background.PNG

Sending JSON Response.

The following example demonstrates how to send JSON response from the Node.js web server.

const http = require('http');

const port = 8000;
const host = 'localhost';

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type' : 'application/json' });
    res.write(`
        {
            'Name': 'Tracy',
            'School': 'Zuri',
            'Track': 'Backend',
            'Course': 'NodeJS' 
        }
     `);
     res.end();
});

server.listen(port, host, ()=> {
    console.log(`Server running on http://${host}:${port}`);
});

Output:

obj.PNG

Conclusion.

In this article, you have learned how to build web servers using the http module that's inbuilt in Node.js that return HTML web pages and JSON data.

Until next time, thanks for reading!