Create Your First Express App

Here, we will learn about how to create an Express Application.

Prerequisites:

  • Node.js must be installed.
  • Any code editor like Visual Studio Code

Now, let’s start by creating a new express application.

Create a folder in which you want to build your express application. Open a folder in terminal and fire a below command.

npm install express

Now, Express is installed, create a new server.js file and open it with your code editor. Then, add the following lines of code:

const express = require('express');

const app = express();

First line here will include an express module from the packages we installed previously. This module is a function, which we then run on the second line to create our app variable.

app.get('/', (req, res) => {
  res.send('Hello World!!!');
});

The above line of call will tell our express server how to handle get request.

This function takes two main parameters.

First is the URL to which we make the request. In the above case, we make a request to “/” that is the root url.

Second parameter is a function with two argument, req and res. req object represent the request coming from the server. res represent the response that we will send to the client.

The above function will simply send a response “Hello World!!!” message

To assign a port, use below code.

app.listen(3000, () => console.log('Listening at port 3000...'));

Now, our basic application is ready. To run the application fire below command in your terminal.

node server.js

By executing above command, you will get “Listening at port 3000…” message on the terminal. Now visit http://localhost:3000 in your web browser. It will simply display “Hello World!!!”.

 

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories