How to Structure my Application in Express.js ? - GeeksforGeeks

07 Dec, 2021
Express is a minimalistic framework that is used to create web servers. It is built upon the HTTP module of node.js and provides a much easier way to manage the code related to the server.
In this article, we are going to discuss how we can structure our express application.
Create Node Project:
Step 1: As the express application is built upon NodeJS so first of all, we have to initialize a node project, write the command below in your terminal.
npm init
 
Step 2: Install Packages
npm install express
Step 3: Create an app.js file. In this file, we write the entire code of the server.
touch app.js
Project Structure: After all of this, our project structure will look like this.
Configure the environment variable: While writing server code several times we need some constant variable in the entire codebase, so we should set some kind of environment variable so that it can be available in all files.This module is used to load environment variables from the .env file to the process object so that later we can easily use these variables anywhere in the codebase.
npm install dotenv 
.env
PORT=3000 // This will be available as process.env.PORT  // You can write any variable here.
Structure of app.js file: Imports are the first thing that should be written inside this file and then some kind of initialization can be there, and later there should be middlewares which are related to entire routes. For example, it can be the express.json() middleware which is used to parse the incoming requests as JSON. After all of this, we can write our routes to execute the particular functionality when the user requests the URL which is starting from the string given inside the middleware.In the end, we can start our server to listen to the client requests. It is safer to establish the database connection first if we are concerned about data persistence.
app.js
// 3rd Party Modulesconst express = require('express');require('dotenv/config');  // Local Modulesconst myRoute = require('./routes/myRoute.js');  // Server Initializationconst app = express();const PORT = process.env.PORT;  // Middlewaresapp.use(express.json());  // Routes will be written hereapp.use('/route', myRoute);   // Server Listen Along with Database // connection(in case of data persistence)app.listen(PORT, (error) =>{    if(!error)        console.log("Server is Successfully Running,                    and App is listening on port "+ PORT)    else         console.log("Error occured, server can't start", error);    });
Setting up Controllers and Route: Routes are the endpoints of HTTP requests to the server or can say a few ways through which a client can interact with the server, we often need a lot of routes in our app so it is a convenient way to set them up beforehand.The controllers are nothing but the code which is going to execute when a client accesses some route. This code can consist of several lines that’s why we separate it from routes files.
myController.j
// Methods to be executed on routesconst method1 = (req, res)=>{    res.send("Hello, Welcome to our Page");}  const method2 = (req, res)=>{    res.send("Hello, This was a post Request");}  // Export of all methods as objectmodule.exports = {    method1,    method2}
myRoute.js
// 3rd Party Modulesconst { Router } = require('express');  // Local Modulesconst myController = require('../controllers/myController');  // Initializationconst router = Router();  // Requests router.get('/', myController.method1);router.post('/', myController.method2);  module.exports = router;
Step to run the application: We can run our express application with the command below, The app.js is the entry point of this application.
node app.js
After the server is successfully running we can start interacting with it, here is one example of GET request via browser,
Output:
Additional Points:
While running the server with node command it keeps running on the basis of the last saved files, if you want the server to be interactive and want to re-run the server every time the code changes, you can use nodemon.Usually, the server is made up of several APIs so that clients can interact, in case if you want to log details of requests which are striking on the server, you can use morgan. It’s just a convenient way to know what’s going on the server.
While running the server with node command it keeps running on the basis of the last saved files, if you want the server to be interactive and want to re-run the server every time the code changes, you can use nodemon.
Usually, the server is made up of several APIs so that clients can interact, in case if you want to log details of requests which are striking on the server, you can use morgan. It’s just a convenient way to know what’s going on the server.
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript