Open In App

Steps to create an Express.js Application

Improve
Improve
Like Article
Like
Save
Share
Report

Express is the most popular minimalistic framework. It is built upon the built-in module HTTP of NodeJS to facilitate the simple and easy interaction between frontend and backend logic through API, and also it enables us to organize our business logic in so much pretty manner. It is much flexible and we can use it for both the web and android. Also, it provides a very simple error handling procedure.

Approach: Below is the fundamental steps to write an express app. Here we are covering the topics like setting up the environment with the installation of modules, creating an application, running the web server, and performing basic communication with the server. Must-Know how to use the node package manager for basic works, basic knowledge of the terminal for installing dependencies and modules, basic knowledge of how a web application works, and a good knowledge of ES6. 

Step by step Implementation:

Step 1: Write this command in your terminal, to create a nodejs application, because our express server will work inside the node application.

Syntax:  

npm init

This will ask you for few configurations about your project you can fill them accordingly, also you can change it later from the package.json file. 

Note: Use `npm init -y` for default initialization

Step 2: Install necessary dependencies for our application.

npm install express

Something like this will be shown on successful installation,  

 

Step 3: The project structure will look like following. 

Create a file app.js, for this article, we will write the whole express code in that file. This will be our folder structure. Now Inside app.js, Import express with require keyword and create an app by calling the express() function provided by the express framework. Set the port for our local application, 3000 is the default but you can choose any according to the availability of ports. Call the listen() function, It requires path and callback as an argument. It starts listening to the connection on the specified path, the default host is localhost, and our default path for the local machine is the localhost:3000, here 3000 is the port which we have set earlier. The callback function gets executed either on the successful start of the server or due to an error.

app.js




const express = require('express');
  
const app = express();
const PORT = 3000;
  
app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, 
                   and App is listening on port "+ PORT)
    else 
        console.log("Error occurred, server can't start", error);
    }
);


Step to run the application: Now as we have created a server we can successfully start running it to see it’s working, write this command in your terminal to start the express server. 

node app.js

Output: You will see something like this on the terminal.

Now with all of this, we have created and run the server successfully, if your server is not starting then there may be some error, try to analyze and read that error and resolve it accordingly. 
Finally, after a successful run if you try to open the URL (localhost:3000) on the browser it will show you cannot GET / because we have not configured any route on this application yet.  

Step 4: Now we will set all the routes for our application.

Routes are the endpoints of the server, which are configured on our backend server and whenever someone tries to access those endpoints they respond accordingly to their definition at the backend. If you’re a beginner you can consider route as a function that gets called when someone requests the special path associated with that function and return the expected value as a response. We can create routes for HTTP methods like get, post, put, and so on. 

Syntax: The basic syntax of these types of routes looks like this, the given function will execute when the path and the request method resemble.

app.anyMethod(path, function)

Example 1: Setting up a basic get request route on the root URL (‘/’ path) of the server.

  1. With app.get() we are configuring our first route, it requires two arguments first one is the path and, the second one is a function that will be executed when anyone requests this path with GET method. The express provides the request and response object as a parameter to all such types of functions.
  2. The req is a giant object which will be received from the user and res is an object which will be sent to the user after the function finishes execution.
  3. Later we are calling status() method it takes an HTTP status code as an argument and when the response is returned, the status will be sent along.
  4. Finally, we are returning the response to the user. The send() method takes a string, object, array, or buffer as an argument and is used to send the data object back to the client as an HTTP response, also there are lots of types of response in express like res.json() which is used to send JSON object, res.sendFile() which is used to send a file, etc.

app.js




const express = require('express');
  
const app = express();
const PORT = 3000;
  
app.get('/', (req, res)=>{
    res.status(200);
    res.send("Welcome to root URL of Server");
});
  
app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running,
                    and App is listening on port "+ PORT)
    else 
        console.log("Error occurred, server can't start", error);
    }
);


Step to run the application: Save this code, restart the server, and open the localhost on the given port. When client request with the appropriate method on the specified path ex: GET request on ‘/’ path, our function is returning the response as plain text If we open the network section in chrome developers tools (press Ctrl+Shift+I to open) we will see the response returned by the localhost along with all information.  

Output:

Example 2: Setting up one more get request route on the ‘/hello’ path. 

  1. Most of the things are the same as the previous example.
  2. The set() function is used to set HTTP header’s content type as HTML. When the browser receives this response it will be interpreted as HTML instead of plain text.
  3. Also in this example, we are not explicitly setting status, it is now concatenated with the statement of sending the response. This is another way to send status along with a response.

app.js




const express = require('express');
  
const app = express();
const PORT = 3000;
  
app.get('/hello', (req, res)=>{
    res.set('Content-Type', 'text/html');
    res.status(200).send("<h1>Hello GFG Learner!</h1>");
});
  
app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, and App is
                      listening on port "+ PORT)
    else 
        console.log("Error occurred, server can't start", error);
    }
);


Step to run the application: Save this code, restart the server, and open the localhost on the given port. Now access the ‘/hello’ route from the browser, The h1 text inside HTML will be shown as a response.

Output:

Step 5: Now we will see how to send data to server.

Sometimes we have to send our data to the server for processing, for example when you try to log in on Facebook you send a password and email to the server, Here we will see how to receive data from the user request. We can send data with the request object on the specified path with appropriate HTTP methods. Till now we were using the browser to interact with the server, but in this step, any tool or frontend form is must be needed to send data because the browser search bar can only send get requests to receive resources from the server. 

Example: Setting up a route to be accessed by users to send data with post requests.

  1. Before creating a route for receiving data, we are using an inbuilt middleware, Middleware is such a broad and more advanced topic so we are not going to discuss it here, just to understand a little bit you can think of this as a piece of code that gets executed between the request-response cycles.
  2. The express.json() middleware is used to parses the incoming request object as a JSON object. The app.use() is the syntax to use any middleware.
  3. After then we have created a route on path ‘/’ for post request. 
  4. const {name}, which is the syntax in ES6 to extract the given property/es from the object. Here we are extracting the name property which was sent by the user with this request object.
  5. After that, we are simply sending a response to indicate that we have successfully received data. If this `${} ` is looking weird to you then let me tell you that it is the syntax in ES6 to generate strings with javascript expression in ES6. We can inject any javascript expression inside ${}.

app.js




const express = require('express');
  
const app = express();
const PORT = 3000;
  
app.use(express.json());
app.post('/', (req, res)=>{
    const {name} = req.body;
      
    res.send(`Welcome ${name}`);
})
  
app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, and 
                    App is listening on port "+ PORT)
    else 
        console.log("Error occurred, server can't start", error);
    }
);


Step to run the application: We are Accessing the route with Postman. It is a tool to test APIs, we can use any other things like Axios, fetch, or any other thing from the frontend or cURL from the terminal, but that will make you divert from the topic, just keep in mind that our express server only demands a path with request object it doesn’t matter from where it is coming.  We have sent the data as a JSON object with the request body and express is sending a response back to us along with the data. It indicates that our goal to send data to the server succeeded.  

Output: 

Step 5: Sending Files from Server

Step 6: Now we will see how to send files from the server.

Several times we need to transfer the resources from the server as per user request, there are majorly two methods to send files one is sending static files using middleware and the other one is sending a single file on a route.
This is our folder structure and we want to serve the files from the Static Files directory as static files, and the image.jpg on a separate route.

Example 1: Serving entire directory using middleware   
Express provides us a middleware express.static(), it accepts two arguments first one is the absolute root path of the directory whose files we are going to serve. 
We can simply use it to serve static files, by providing to app.use().

Syntax:

app.use(path, express.static(root, [options]));
  1. First of all, we are importing an inbuilt module `path`, because later we are going to use one of the functions provided by this module.
  2. We are simply mounting a middleware at the ‘/static’ route.
  3. The static() middleware requires an absolute path so we use the path module’s join method.
  4. The join() method takes two parameters and joins them as a path, in NodeJS we have a global attribute __dirname which contains the path of the directory in which the current file exists.
  5. We are providing that joined path to middleware so that it can start serving the files inside that directory on the given path.

app.js




const express = require('express');
  
const app = express();
const PORT = 3000;
  
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'Static Files')))
  
  
app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, 
                   and App is listening on port "+ PORT)
    else 
        console.log("Error occurred, server can't start", error);
    }
);


Step to run the application: This will be the returned response when we request some static file from the directory which we are serving as static. Here you can see we have received an HTML file as a response for ‘/static/random.html’. The same things happen when we request for ‘/static/1.jpg’.

Output:

Example 2: Sending a single file on a route with the sendFile() function.
This function accepts an absolute URL of the file and whenever the route path is being accessed the server provides the file as an HTTP response. This process can be thought of as a single endpoint of the express.static(). It can be useful when we have to do some kind of processing before sending the file.

Syntax:

res.sendFile(fileUrl)
  1. We are creating a get request route on the ‘/file’ path
  2. After then we are creating the absolute path by joining the path of current __dirname and the name of the file we want to send and then passing it to sendFile().
  3. Then route sends the image.jpg file to the user as an HTTP response.

app.js




const express = require('express');
const path = require('path');
  
const app = express();
const PORT = 3000;
  
app.get('/file', (req, res)=>{
    res.sendFile(path.join(__dirname,'image.jpg'));
});
  
app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, and App is listening on port "+ PORT)
    else 
        console.log("Error occurred, server can't start", error);
    }
);


Output: After running the server, When we request the route ‘/file’ the server sends the image.jpg file as a response.



Last Updated : 06 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads