How to create a basic web server with Node.js

Node.js has been one of the most popular choices for server-side development since it was first released over a decade ago. It’s still relatively new compared to PHP and other back-end technologies, but it’s widely adopted by big tech companies like LinkedIn, PayPal, and Netflix.

This article describes how to create and run your own web server using the Node.js and Express.js web frameworks.

Associated technologies and packages

Node.js is a JavaScript runtime engine built on top of Chrome’s V8 engine that allows you to run JavaScript code outside of your browser. Traditionally, JavaScript Document Object Model (DOM) programming languages ​​add interactivity to your website.

Because of this, the DOM only exists in web pages, so JavaScript code has been limited to executing only in the browser. Node.js allows you to run JavaScript on the command line and on the server. Therefore, install Node.js and npm on your machine before you start.

Express.js, on the other hand, is the minimal web framework that has become the de facto backend framework for Node.js. However, Express.js is not required. The integrated module can still be used http A Node.js module to create servers. Express.js http It is a module that provides a simpler API with all the configurations you need.

Build a web server

To better organize your code, you can start by creating a folder with all your files and dependencies. Express.js is not a built-in Node.js module and must be installed using npm.

Read more: What is npm?

Run the command to install the Express.js package npm install express In a terminal or a command prompt. Make sure you are in the project directory before installation.

Install Express via npm

When you’re done, you can use your text editor or IDE of your choice to open the folder and create a new file named. server.js.. To use the Express.js package, import this instance first, then server.js Such files:

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

The main purpose of the web server is to respond to requests from different roots using the appropriate management functions. This code handles all GET requests made at the root (“Https://www.makeuseof.com/”) Go through and respond with “Hello World!”.

app.get("https://www.makeuseof.com/", (req, res) => {
res.send('

Hello World

');
});

Likewise, you can display dynamic content and perform other operations, depending on the path and type of request. This can be done using root parameters indicated by semicolons. : Before the parameter.

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

Welcome to ${req.params.name}!

`);
};

In the two examples above, the first line shows the use of .. to have() Express.js methods that take two parameters: an endpoint or root, and a callback handler function that takes request and response objects as parameters. These two parameters are sent automatically when you make a request.

On the second line, the answer is .send () The method of the response object. You can enter any text or HTML in parentheses. Access for dynamic routes req.params.name (Because you used it /: first names(From query object) returns the value of dynamic route parameter (from query object)first names in that case. )

Finally, to start listening for incoming requests on the port, .. Listen() A method that receives a port number to execute when executed successfully and an optional callback function.

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

This example used port 5000, but you can change it to any valid port. That’s all the code you need to build a basic web server using Node.js and Express.js. The same concept can be extended further to make other requirements such as: Position, To put, Or Wipe off To another route, here’s how server.js The file looks like this:

Server test

To run the code and start the server Node server Terminal commands or project directory command prompt. This will perform the callback function provided in. .. Listen() Method.

Express server running

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

Express.js-root root demo

Likewise, when accessing the next dynamic route http: // localhost: 5000 / muoThe second handler function is executed and you should see something like this:

Express.js-Dynamic route demo

Press to stop the server Ctrl + C Windows or Cmd + C On macOS.

Node.js can do even more

The popularity of JavaScript is growing exponentially as developers use it not only on the back end but also on the front end. This eliminates the need to learn multiple programming languages ​​and allows you to start your journey as a full-stack web developer using only JavaScript.

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

Featured Image of GoWeb Server
How to create a basic web server with Go

Ready, Golang: start building your web server with Go.

Read more

About the Author

..


Source link

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