How to create a basic web server in Node.js

Node.js has become one of the most popular choices for server-side development since its initial release over a decade ago. Although it is still relatively new compared to PHP and other backend technologies, it has been widely adopted by tech giants like LinkedIn, PayPal, Netflix, etc.

This article will teach you how to build and run your own web server with Node.js and the Express.js web framework.

Technologies and packages involved

Node.js is a JavaScript runtime built on Chrome’s V8 engine that allows you to run JavaScript code outside of the browser. Traditionally, the JavaScript programming language has been used to manipulate the Document Object Model (DOM), adding interactivity to websites.

For this reason, the JavaScript code has been restricted to run only in the browser, as the DOM only exists on web pages. With Node.js, you can run JavaScript at the command line and on servers. Therefore, it is essential to install Node.js and npm on your machine before starting.

On the other hand, Express.js is a minimalist web framework that has become the de facto backend framework for Node.js. However, Express.js is not a necessity. You can still use the http Node.js module to build your server. Express.js is built on top of the http module and provides a simpler API with all the necessary configurations.

Build a web server

To better organize your code, you can start by creating a folder where all the files and dependencies will reside. Since Express.js is not a built-in Node.js module, you will need to install it using npm.

Read more: What is npm?

To install the Express.js package, run the command npm install express on your terminal or command prompt. Make sure you are in the project directory before installation.

Install express via npm

When done, you can open the folder using any text editor or IDE of your choice and create a new file named server.js. To use the Express.js package, you must first import and create an instance of it in the server.js file like this:

const express = require('express');
const app = express();

The main purpose of a web server is to respond to requests from different routes with the appropriate handler function. This code handles all GET requests made at the root (“/”) and responds with “Hello World!”

app.get('/', (req, res) => {
res.send('

Hello World

');
});

Likewise, you can display dynamic content and perform other operations depending on the path and type of request you make. This can be done using the route parameters, indicated by the semicolon : in front of the parameter.

app.get('/:name', (req, res) => {
res.send(`

Welcome to ${req.params.name}!

`);
};

In the two examples above, the first line represents the use of the .to have() Express.js method which takes 2 parameters: the endpoint or the route, and a callback handler function which takes requests and response objects as parameters. These 2 parameters are sent automatically when you make a request.

In the second line, the answer is made through the .send() method on the response object. Inside the parenthesis, you can enter any text or HTML code you want. In the case of dynamic routes, access req.params.name (since you used /:Name) of the request object will return the value of the dynamic route parameter (name in that case.)

Finally, to start listening for incoming requests on a port, you can use the .Listen() method that takes the port number and an optional callback function to execute on successful execution.

app.listen(5000, console.log('Server is running on port 5000'));

I used port 5000 in the example, but you can change it to any valid port. That’s all the code you need to build a basic web server with Node.js and Express.js. The same concept can be extended further to make other demands such as PUBLISH, TO PUT, Where WIPE OFF to other routes. Here is how the server.js the file will look like:

ExpressJS code for web server

Server test

To run the code and start the server, run the node server on your terminal or at the command prompt in the project directory. This will perform the callback function you provided on the .Listen() method.

Express server running

To confirm that the server is running, open a web browser and visit http: // localhost: 5000

Express.js - root route demo

Likewise, if you are visiting a dynamic route such as http: // localhost: 5000 / muo, the second handler function will run and display:

Express.js - Dynamic route demo

To stop the server, press Ctrl + C under Windows or Cmd + C on macOS.

Node.js can do more

The popularity of JavaScript is increasing sharply as developers use it on both the front end and the back end. This eliminates the need to learn multiple programming languages ​​and helps you start your journey as a full-stack web developer using only JavaScript.

If you decide you’d rather try out Google’s programming language, building a basic web server is a great starter project.


featured image for Go web server
How to create a basic web server in Go

Ready, Ready, Golang: Start building web servers with Go.

Read more


About the Author


Source link

Comments are closed.