Express.js is a Node.js framework to develop the backend APIs of web and mobile application. It is Open San NPM package and is generally installed after creating a Node.js application.
This is where Express.js shines and does the one job perfectly for which it was created, which is, creating API endpoints. It adds the functionality of middleware and routing with ease in a Node.js application.
Some difference between Express.js and Node.js are -
In this instance, we will write the same app in Express.js and Node.js. First, we will write the app in Node.js. Here, we are using the createServer() method and are writing the response in a template language.
Now, we can go to http://localhost:3000/ and see the output.
Next, we will create the same app in Express.js and see the difference. We don’t need the template code for the entire page. Besides this, the code is much cleaner and easier to understand.
We can go to http://localhost:8080/ and we can see the result.
Since Express.js is a framework for Node.js, the basic requirement is to have Node.js installed on the system. The installation of Node.js can be done in many different ways, depending on the operating system. The best way is to go to the Node.js official site https://Node.js.org/en/ and install it.
Node.js comes with NPM install and it is required, because Express.js is an external node package, which needs to be added in a Node application.
To show how that works, we will create a Node.js application and add Express.js to it. First, create a folder and then make changes to it.
Now, give the command ‘npm init’ to initialize a node app. We can leave most of the questions as default by pressing enter. But we'll give the entry point as server.js. We’ll also assign an author. And finally, enter ‘yes’ for the last question.
This creates a package.json file will in the same directory, and we can install npm packages now. Then, we’ll add express in our Node.js application by giving the command npm i express from the same directory in the terminal.
Next, we’ll create a file server.js in the root directory and add the below code in it. Here, we are first importing express and using it in an app. After that, we’re also declaring a port and making it equal to 3000. Next, we have a GET request to /, where we will send Hello Express to the client.
Finally, we are listening at port 3000 for incoming requests.
Now, we will start the express app by running the command node server.js from the terminal.
Then we will go to http://localhost:3000/ and see the text Hello Express in the browser.
This is a frequently asked interview question on express.js.
Express has an in-built route support, so a developer can write responses to specific URLs with ease. We can also pass parameters to these routes, which add to the capabilities of the app. Express also supports multiple templating engines, through which you can generate static HTML for a web browser. If you follow this approach, the pages will be generated by the server, and there will be no need to write client code in Angular or React.
Without Express.js, we would have to write complex logic in Node.js, which is both tedious and time-consuming. Express.js code is minimalistic, efficient, and easily understandable by programmers, and because of it easily scalable.
Node.js programs are really fast because they implement event loops and get rid of all inefficiencies. With the power of Node.js and ease of an Express.js, we can build the backend for powerful and scalable web apps in no time.
There are three functions, which are available as arguments in Express.js route handler function. The route handler functions are get, post, put, delete, and others. These are mentioned below.
We will take a small example containing all three arguments. We need to create a Node.js application first by creating a folder and adding node by npm init -y command.
After this, we will install express in it using npm i express command.
Next, we’ll create a file with the name server.js and add the below code in it. Here, we shall first see the use of next() to pass control to the next function. After that with res.send() we will send the text Node.js Developer to the client.
We also have a route to get the id of the user with req.params.id.
Now, start the server with node server.js from the command line and then go to http://localhost:3000/ in the browser. We will see the below messages in the terminal.
Also, if we go to the route like http://localhost:3000/22, we will get the below console log in the terminal.
Expect to come across this popular question in Express.js interview questions for freshers.
So, we don’t use Express.js over Node.js but with Node.js. We take the speed and performance of Node.js along with the simplicity of Express.js to create scalable and performant web-apps APIs. This is the reason, we never use Node.js without Express.js in production and they always go together. Node.js along with Express.js, is part of two popular stocks i.e., MEAN stack and MERN stack.
The growth of Node.js should be credited to Express.js also, which has made Node.js really easy to use. Just as bootstrap led to the success of CSS, similarly Express.js led to the success of Node.js.
Yes there are many alternatives to Express.js and some of them are even better then Express.js. ExpessJS was released around the same time as Node.js i.e., in 2010. So, it has become the de-facto framework for Node.js.
Fastify - As the name suggests it’s a Fast framework for Node.js, which can serve up to 30 thousand requests per second. It comes with async-await support out of the box, which can be easily used in the code. We can extend it via hooks and plugins. Fastify is also TypeScript ready, in which you can use TypeScript out of the box.
Below is a small example to create a simple GET route in Fastify. We are using async-await through which we can handle promises and errors better. For the below code to work, we need to install Fastify in our Node application by below command.
npm i fastify
Now, we can go to http://localhost:3000/ and see the correct output.
Koa - It is a modern and new framework for Node.js. Infact the Koa framework is created by some of the people in the Express.js team. It has been built ground up to use modern ES6 features like async-await and generators. One of Koa’s drawbacks is that it doesn’t come with an inbuilt router, and we need to install an external library of koa-router.
So, we need to add these packages to a Node.js application, in order to use Koa.
npm install email@example.com @firstname.lastname@example.org
Now, we can go to http://localhost:8080/ and see the correct output.
Scaffolding is the process of creating a skeletal structure of a project. The production projects require a lot of modules to be added in the project before even starting to write the code. This is where scaffolding is used and there are many packages available for it in Express. We will now look at a scaffolding project.
The express-scaffolding-cli is a simple and easy to use scaffolding tool, which creates a complete express project with just giving the project name.
We can use it with the latest npx command, without even installing it. So, we’ll give the command npx express-scaffolding-cli from the command line to create a new project.
It will create a project within no time and with it a new directory with scaffoldingEx will be created. So, we will change to it and npm install to add all the packages.
Now, a project will be created with routes, middleware, authentication, and error handling. We only have to give the database name in the default.json file. You should have the MongoDB running locally through compass, for this setting.
Now, we need to give the PORT number in the server.js file.
Now, in the terminal, we have to run the command npm run dev as per the documentation in https://www.npmjs.com/package/express-scaffolding-cli and our server will run successfully.
Now, go to http://localhost:3000/ and we will be able to see the message of HomeRoute sent by the server.
With Express.js Generator or simply express-generator, we can quickly generate a daily complex skeleton of an Express.js app. Now, the app generated comes with a lot of structures and even Jade template.
To generate an app with express-generator, first we need to create a folder with the name of the app. After that go inside the folder and then give the command npx express-generator to create the app.
Now, we need to install the dependencies in the app with the npm i command.
Finally, we will start the app with the npm start command.Now, we can go to http://localhost:3000/ and see that we have an html output.
Our app starting point is app.js file, which contains all the required imports and it’s call to two routes.
The route at index.js contains the title of Express and this gets passed to the index.jade file.
Now, the templating engine of Jade, uses its own language to show the content in http://localhost:3000/
As we can see from the above example, a fairly complex app was set up with different routes and templates. These templates will be shown on the client browser, when they reach the endpoints.
By using the templates, we don’t even need a frontend client code and the code will be generated by the backend itself.
By default, debugging is turned off in Express.js. As Express.js and in turn Node.js are not meant for the browser, so we cannot see the logs in the browser console.
To turn on logging, we have to use a bit of a different command depending on the operating system, when we are launching the application. On a UNIX operating system, we use the below command.
$ DEBUG=express:* node index.js
But on a Windows operating system, we use a different command:
> set DEBUG=express:* & node index.js
We will create a small Express app and enable debugging to check it out. First we need to create a new folder and change directory. After that we shall use the npm init command with -y option, to create a package.json file, which is a must for any Node.js app. Notice that we have given the -y option, else we would have to answer a lot of questions.
Next, we will install express in our app by the below npm command, as it comes as an external package.
Now, create a file index.js and add the below code in it. This simple code will send the message Hello World, when someone goes to the home route from a browser.
Now, instead of running the node command by node index.js , we will run by the command which we have learned earlier.
Now, our advanced debugging is enabled in an Express App.
Pino is a small and fast logger, which can be used in express apps. It logs additional information which is very useful for debugging.
First, we need to create a new folder and change directory. After that we use the npm init command with -y option, to create a package.json file, which is mandatory for any Node.js app. Notice that we have given the -y option, or else we would have to answer a lot of questions.
Next, we will install express and two pino packages. One is for normal logging and the other is for http logging.
Now, create a file index.js and put the below code in it. Here, we are first importing express, pino-http and pino. The log from the app.get() is using the pino-http module and has been done by req.log.info(). The simple log inside app.listen is using the simple pino, with logger.info(). Also notice that we can pass the number separately in it.
Now, when we run the app with node index.js, we will get the detailed log which includes the timestamp, pid and hostname also.
Now, go to http://localhost:3000/ and we will get the detailed log of the http request being made.
It's no surprise that this one pops up often in Express.js questions.
The debug logger is more like our console logs, but it shows the log in a beautiful and colorful way. Additionally, you can turn certain modules on and off for logging. Let’s take a look at an example.
We need to first create a new folder and change the directory. After that, we need to create a Node.js application by giving the command npm init -y. Next, we will install express, debug and http modules in it by giving the command npm I express debug http from the command line.
Now, we are creating a basic app with the http module and enabling logging in it. The line const log = debug(‘http:server’), means that our server is called by that name.
Now, when we go to the terminal and give the command DEBUG=http:server node index.js , we will see the below output from Line 6 and Line 12.
Now, go to http://localhost:3000/ and we will see the log output from Line 9 from index.js in our console.
As mentioned earlier, one of the main features of the debug logger is to do selective logging. To show that we will create a fake error in our app, which is using setTimeout() and running after 1 second. Also, notice that we have a new errorLogger with the name http:error declared.
Now, to see only this log, we have to change our command in the terminal to DEBUG=http:error node index.js , we will see the below output fromLine 13, after 1 second.
Now, if we turn on all the logs with *, we will see all the logs in the terminal.
An Express.js app is basically a Node.js app, with express installed in it. We have to create a basic Node.js app and then add express to it, which is available as an external npm package.
So, open any terminal and create a directory and then navigate to the directory using the cd command. After that create an NPM project by giving npm init -y command. If we omit the -y flag, we have to respond to some questions manually with ‘yes’.
Next, we need to install the express package through npm.
Now, create a file index.js in the route directory and add the below lines in it. The first line is used to import the express module, which we have just installed. The second line is used to create our app variable, using express. We are going to use this app variable throughout our app.
The next lines of code tell that we are doing a GET request, using the app which we have previously created. It takes two parameters and the first one tells the path on which this action will be taken. It is also known as route and it is ‘/’ in our case.
The next argument is “req” and “res”. Here, the ‘req’ is the request which was sent to the server and the ‘res’ is the response, which will be sent back from the server. We will be sending back a simple text of Hello Express to the client.
Lastly, we will listen to some port for the request. We generally listen to port 3000 for backend, but we can take any port. Also, notice that we have a second argument to listen function, which is generally used for logging.Now, we will start the server from the terminal by giving the command node index.js and we will get the output of the log.
Lastly, in any browser go to http://localhost:3000/ and you will see the response from the server.
The request object is used to handle the data which comes to the server through string or JSON object. Express will receive data from clients through three types of req objects i.e., req.params, req.query and req.body. We will learn in detail about it through examples.
First, we shall create a simple Node.js project and install express in it. We will do it by creating a new folder and then changing to it. After that, giving the command npm init -y to create a Node.js project. After that we will install express in the app by giving npm i express command.
Now, we will create a file server.js and add the below code in it. First, we are doing the required imports while also listening on PORT 3000 for incoming requests. Now, with req.params we can get the data passed in the url.
Now, go to http://localhost:3000/22 in any browser and we will see the id in the running server.
We generally get the data from the client in a POST request through a JSON object. We will add a new /login path in which we are console logging the email and password from req.body.
Notice that we need to use a middleware of app.use(), so that we can receive json. Also, we need to send back a success request with res.send() to the client.
Now, we need to send a POST request through Postman, or else create a frontend and take the data from the user and submit it as a JSON object.
In Postman, we send a JSON object with email and password.
Now, with the server running, we will get both email and password received on the server.
The response object or the res object, is used to send the data back to the client. It generally happens after the request is sent from the client in the req object. So, it is a part of the request and response cycle.
Now, with the res object we have many methods like send(), status(), append(), redirect() and render(). We will look at some of them through an example.
We need to first create a simple Node.js project and install express in it. We will do it by creating a new folder and then changing to it. After that, giving the command npm init -y to create a Node.js project. After that we will install express in the app by giving npm i express command.
Now, create a file server.js and add the below code in it. First, we are doing the required imports and listening on PORT 3000 for incoming requests. Now, with req.send we can send any data, when the user comes to the / route.
Now, when we go to the / directory from the browser, we will get Hello Express shown.
Next, we will look at res.redirect, which will redirect any route to the other route. In our case if we go to /help, we will be redirected to /user.
Now, when we go to localhost:3000/help we will be redirected to http://localhost:3000/user in the browser and will see the user path text.
We have also created a route in which if we go to any route other than the one done earlier, we will get Page Not Found text and also a status of 404 will be sent. We are using both res.status() and .send() chained to it.
Now, go to any non-existent route and we will shown Page Not Found text.
Next is a function in Express.js, which can be passed along with res and rep objects. It is used to pass control to the next middleware. There can be cases where we don’t want to complete the function in the current middleware and do the additional task in the next middleware. In these cases, next() is useful.
We will go through a simple example to understand the same. We will first create a new Node.js application by creating a directory and changing to it. Then will initialize a package.json file with the npm init -y command.
Next, we will install express in the app by giving the npm i express command.
Create a new file index.js in the root directory and add the below code in it. Here, we have two middleware, and we want to pass the control from the first to the second.
But notice in the first, we are not using the next function.
Now, run the server by node index.js command and go to the localhost:3000 from the browser. We can see that we only got the first message and not the second message from the second middleware.
Now, we will add next() in the first middleware and this is where the control will be passed to the second middleware.
Now, again run the server by node index.js command and go to the localhost:3000 from the browser. We can see the messages from both middleware and were able to pass the control from the first to the second one.
A common question in Express.js interview questions and answers, don't miss this one.
To send data from client browser to server, we have many methods. We can also pass the data as a query parameter using GET requests. But it is not advisable to send through GET because the data will be exposed in the query parameter in the browser link.
To send data the POST request is created and we should send through it only. We are going to send the data through POST in express and going to learn about it next.
We will first create a new Node.js application by creating a directory and changing to it. Then will initialize a package.json file with the npm init -y command.
Next, we will install express in the app by giving the npm i express command.
Now, create a file server.js and import express and give a port. After that we are using a middleware for json. It is required because we are going to pass our data as JSON to the backend.
Next, we will create a post request and pass the name and email in the body. We have also created a function .listen() to listen for the function in localhost port 8080.
Now, for checking our POST request, we need to use a postman app. Here, we need to send the application header as JSON and in the body pass name and email as json objects.
After that hit the Send button and the POST request will be sent successfully to the server.
To download a file through Node.js requires a lot of effort and the code can get complicated soon. But the process is very easy with express.
We will see the same through a small example app. First create a new Node.js application by creating a directory and changing to it. Then will initialize a package.json file with the npm init -y command. It will give all options as yes and if we don’t give it, we will have to manually type yes.
Next, we will install express in the app by giving the npm i express command.
Next, add an image file in the root directory. We’ll add desktop.jpg in the root directory.
Now, create a new file index.js. First, we will import the required express import. Then we have an app.get() function for the home directory. Now inside the get function, in the response object we are using the download function and passing our image desktop.jpg.
Lastly, we are listening at port 3000 for incoming requests.
After that start the node server by giving node index.js in the terminal.
Now, when we go to localhost:3000 the image file desktop.jpg will be downloaded automatically.
Models are required in Express JS, when we are integrating Express with databases, especially MongoDB databases. It defines the way in which the data will be stored in the MongoDB database. Let us understand it through an example.
We will first create a new directory, then change directory and initialize a Node project with the npm init -y command.
After that we also need to install the package of express and mongoose.
Next, we need MongoDB running from the cloud or local system. We have the local MongoDB running on our system and showing through Compass.
Now, create a file server.js and here, we shall first import express and mongoose. After that, we shall create a simple GET route. Next, we will use mongoose to connect to our local running database through mongoose.connect().
Now, we are using mongoose.connection.once() to open the database connection and show the success or the error messages, depending on the status.
Finally listening to incoming requests on port 3000. Now, in the terminal run the server by node server.js command and we will see the message that it was able to connect to the database successfully.
Now, we will create our model for the database. So, create a folder Models in the root directory and create a file emp.js in it. Here, we are creating a schema for the employee which basically contains the structure. So, we have empName and empEmail in the schema.
Now, we will use this Model in our server.js file. We need to import the Model first and also use the express.json(), because we are going to send json data.
Next, create a POST route to add the employees. Here, we are using our model to send the empName and empEmail. After that we are using emp.save() to save the data in the MongoDB database.
Now, we will send the POST request from Postman as JSON object and it will be a success.
We can also check in MongoDB Compass to see if the data got saved successfully.
A template engine is used to write static code of HTML files. All of these template engines have their own language and are used to write the code for templates. When a client goes to any route which serves a template file, these template engines convert them in pure HTML code and send them back to the client.
This is a very efficient and fast way to generate HTML files at the server, instead of relying on frontend client-side code through languages like Angular, React, or Vue.
The popular template engines for Express are Pug, Handlebars, Mustache, and EJS. Let’s look into an example of Pug, which is one of the most popular templating engines.
First create a new Node.js application by creating a directory and changing to it. Then initialize a package.json file with the npm init -y command. It will give all options as yes and if we don’t give it, we will have to manually type yes.
Now, install express and pug into the node application by using the command npm i express pug in the terminal.
Now, create a file server.js in the root directory and put the below code in it. Here, we are first importing express and then setting it to app. Now, with this app we are using pug as our view engine.
After that we are having a GET function to /. Inside the GET function, the res object is rendering the home.
Lastly, we are listening to all incoming requests are localhost 3000.
Now, create a views folder and inside it home.pug file. Now, in this file we will put a h1 and a p with content. Notice the coding style for pug, which is totally different compared to html.
Now, go to http://localhost:3000/ and we will get the pug file rendered as html on the browser.
One of the most frequently posed Express.js interview questions for experienced, be ready for it.
Sometimes we need to get the full URL in the server, and we can do it through the express app. We will look into the same in this example.
We will first go through the basic setup step and create a new Node.js application by creating a directory and changing it. Then will initialize a package.json file with the npm init -y command.
Next, we will install express in our app by giving npm i express from the command line.
Now, create a file server.js and add the below code in it. Here, we have an app.get(), which is looking at all routes. Here, from the request, we are first getting the protocol which is basically the type of request - http or https.
Next, we are getting the host which can be any address on the internet or localhost. We are also getting the URL, which is basically the part which comes after the localhost. Next, we are also getting the port on which the request is coming.
After that we are just constructing the full URL, using all the parameters and sending back to the client.
Now, start the server with node server.js in the command line. After that go to any url and, we will get the complete URL printed.
A cookie is a small text file, which is stored in the client browser. When a client visits any website, through their browser and logs in to the site or fills some kind of a form, this data will be passed back to the client from the server, with some unique id which identifies the user computer.
Now, whenever the user visits this website the saved data like username and password will be auto filled. And the user can also be given a unique experience like adding their name in login.
The modern-day cookies are also known as HTTP cookies as they are used for internet browsing. It got its name from the Magic Cookies, which were before the internet era and used to store login information to a database system.
There are mainly two types of cookies -
The session and the cookies are both used to store user information for various purposes. They help the data to be passed between different parts of the website. There is a difference between a session and cookies.
Sessions are saved on the server side i.e., in the case of an Express server, it will be stored on the stored server. But they are also temporary and get deleted the moment the user goes away. Suppose a user logs into a site, then their data will be stored in the session variables, for better programming purposes. The data stored in the server is also very much secure in comparison to the client and cannot be easily compromised. Each session of a user is unique so separate data is maintained for the same.
On the other hand, a cookie is a text file of a maximum size of 4KB, which is stored on the client computer. It is always stored as a string and is sent the first time the user visits the website. Cookies have many uses and they also used to keep track of users’ web-surfing behaviour, by tracking their browser history. Like when you visit a popular video streaming site and surf videos, the next time that site will show videos based on your earlier visit.
Cookies are an important part of any backend project. They are used for various tasks like saving user information, form, data, and others. We will learn how to implement cookies in an Express.js project.
First create a project directory and go to it. After that initialize a node project by giving the command npm init -y from the terminal.
After that we will install express and cookie-parser in the project. The cookie-parser helps us to manage the requests made by the user to the server.
Next, create a file server.js and inside it, put the below code. We are importing the express and cookie parser first. After that we will use express through the app and through the app using the cookie.
Next, in an app.get in the root directory, we are using res.cookie() to send cookie data from the server to the client browser. Next, we are just sending a message to the client browser, that the cookie was saved successfully.
Now, in the browser go to http://localhost:3000/ and we will see the message Cookie Saved Successfully. After that open the developer tools and Go to Storage and then expand Cookies and we will see our cookie been saved.
Express and Django are both used for backend development, but they are different in many ways. These are the main differences in both platforms:
As the name suggests the Middleware are used in the Middle of a Request response cycle. In technical terms, they are the function invoked by the Express routing layer, before the final request handler.
Middleware are used to perform the following tasks -
One common rule is that if middleware doesn’t end the request-response cycle, it should call the next middleware function to pass the control. If we don’t do this, the request will be hanging.
We will see a simple middleware in action next. Here, if we have to route /contact, which will first console log the current time. After that it will pass the control to the next function, which actually sends the request back to the user.
Now, when we go to http://localhost:3000/contact we will get the below in console of running node app.
We will also get our response back
There are various types of middleware available in an Express application. They are -
Now, we will look at a simple example of a third-party middleware known as body-parser. It is used to parse requests which have a payload.
We are creating a simple node project and installing the dependencies for express, body-parser and EJS.
Now, we will add a simple form using the templating language of EJS. Create a file SampleForm.ejs and put the below content in it.
Now, in the index.js file we will create a basic Express.js app, without the body parser.
Now, run the app with node index.js command from the terminal and there will be a form to submit in http://localhost:3000/ . When we submit the form, we get the below error, because node cannot parse the json.
Now, we will add a body parser in our index.js file, to solve this issue.
Now, when we submit the form, we get no error and the data is received in the server.
A staple in Express.js interview, be prepared to answer this one.
The method responses or the res object is the response sent by the server to the client. There are many types of responses which can be sent to the client and we will look into them next.
The most common method for res object is the .send(), through which we can send any data to the client. Below is a common example for the same.
Here, if the user goes to the / route in their browser they will be shown the Hello Express text on the browser.
We can also send the status code with the .status() method. These HTTP status codes are very important and interpreted by the client browser as success or failures. In the below example, we have also chained the send method.
There is a shorthand syntax also, which combines both status and send method chaining. The method is called .sendStatus(), and it is used as below.
We can also define headers in our responses to the client and for this we have the .append() method. Below is an example of the same.
The .redirect() method is a very important one, as it can redirect to any route in the web-app. We have to just pass the route as a parameter.
We can also prompt the client to download a file with the .download() method. Below is an example of the same.
Express can connect to different types of databases. It can connect to NoSQL databases and Relational databases also. It connects very well with the two popular databases - MySQL and MongoDB. We will see to connect it to a MongoDB database next.
First, we will go through the basic setup steps and create a new Node.js application by creating a directory and changing to it. Then will initialize a package.json file with the npm init -y command.
Now, we will install the required package of express and also the package of mongoose. Mongoose is a package built for express applications, which makes it very easy to interact with mongoDB databases. We will install them with npm i express mongoose from the command line.
Now, create a file server.js in the root directory and add the below code in it. Here, we are first importing express and mongoose and after that using it in the app. We have also created a PORT and MONGOPORT variable with different values of 3000 and 5000.
After that we are using mongoose.connect() to connect to the local MongoDB instance. If the connection is successful, we are showing a success message or else an error message.
Lastly, we are listening to the connections at PORT 3000.
Now, from the terminal run the command node server.js and we are successfully connected to mongoDB.
We need to show errors or the well-known 404 page to users who go to a non-existent page in our website. We will learn to do that next.
We will first go through the basic setup to create a new Node.js application by creating a directory and changing to it. Then will initialize a package.json file with the npm init -y command. If we don’t specify the -y flag, we need to hit enter to a lot of default fields.
Next, we will make it an express app by adding the express package through npm.
Now, we will create a file server.js in the root directory. Here, we are first doing the import for express and then using it in the app.
Now, we have three routes here, first for the home and second for contact. The third one contains ‘*’ and it contains all the routes not present in the first two. If a user tries to go to some route which is not mentioned, they will be shown ‘Page not Found’.
One thing to keep in mind, is that this wildcard(‘*’) route, should always be the last route in our code.
Lastly, we are listening to all client requests on port 3000.
Now, start the server by giving node server.js in the terminal.
Now, if we go to any route except / or /contact, we will be shown the error message.
CORS stands for Cross-Origin Resource Sharing. It is enabled in the browser by default and because of it a client running on a different network, cannot access the server running on a different network.
Here’s an example. First, we will have our Node runtime installed and created using npm init -y. We will also install express and cors in our Node.js app.
Now, we will have a simple Express server in which we are sending an array of objects to the client, when coming to home root.
First start the node server by running node index.js from the terminal and navigate to http://localhost:3000/ and we will get the array of objects back.
This is allowed because our server and client - both are in localhost. Now, to make the request from a different client network, we have to go to some other site. We are going to https://www.knowledgehut.com/ and opening the console. Here, we will be using the inbuilt fetch api to goto the server endpoint at 3000.
Notice that we are getting a CORS error and not able to get the data.
In order to allow requests to our server endpoint from knowledgehut.com, we need to add it in cors middleware. We have already installed cors earlier, so we are importing it first.
Now, when we go back to knowledgehut.com, and give the same fetch request we will get the data back successfully.
It is always a bad idea in production projects to have configuration data in the server.js file or the main file. In production projects for Express.js, we configure the properties in two ways. They are -
We will look into the config.js method to store the configuration properties. First, we will have our Node runtime installed and created using npm init -y. We will also install express and mongoose in our Node.js app.
Now, create a file config.js and in this file, we will store all the configuration related to our project.
Here, we are storing the app and db configuration both, which in small projects we give in the root file only.
Next, create a file db.js and in it we can use the configurations from config.js file directly by just importing it and using it.
Here, we are just de-structuring the config object and taking the db values from it. After that we are further de-structuring and taking the host, port, and name from it.
After that create a file App.js and inside it alo, we are using the data from the config object in the config.js file.
Now, when we run the node app.js command, we will see the port number correctly connecting.
Routing is the way in which the server responds to a clients request to a particular path, when it comes through different protocols like GET, POST, PUT, DELETE. In common words, it is the function which gets called then the user goes to a URL on the web-app.
We will look at basic routing through an example. So, we will first set up the Express JS application by creating a Node.js runtime, through npm init -y command.
After that, install express in it through npm i express command.
The basic routing is done through app.method(path, callback) function. In our example, we are using the get and the post methods.
The app.get(), have a route to the root directory and just sends a text back to the client browser.
The app.post(), have a /submit route in which we are logging the plain text, which we will receive from the client browser. After that we are sending the ‘Data received Successfully’ message to the client browser.
First start the server by giving node server.js in the terminal. Now, check the GET route go to http://localhost:3000/ from the browser and we will see the text Hello Express in it.
The POST route requires a form to be submitted from the frontend, or we can do it from the postman app. Here, we are sending a plain text, because our server is expecting a plain text.
Now, in the server logs also we are receiving the text, which we have sent.
We can also use modular routes using express.router(), with which we can reuse a route. Create a new file router.js and add the below content in it. Here, we are using the router.route() to the same path. After that we have a .get() and .post() route.
Now, we will use the routes in the app.js file. Here, we are importing the router.js file and after that with app.use(), using it in different ways.
Now, go to http://localhost:3000/dev/nabendu/22 and we will get the welcome text served from router.js file.
We can also do a POST request from http://localhost:3000/tester/shikha/24 and we will get the Data received text served from router.js file.
JWT stands for JSON Web Tokens. They are a very secure way of authentication of the client with the server. Let's look at an example, where we will get the JWT token of a specific user. We will be generating it on the server and sending it back to the client. Each client will have a unique JWT token.
We will first set up the Express JS application by creating a Node.js runtime, through npm init -y command. After that we are installing express, jsonwebtoken and dotenv in it through npm i express jsonwebtoken dotenv command.
Next, create an .env file and give a TOKEN_SECRET in it. We can use any long random string in it.
Now, create an app.js file. Here, we are first doing the required imports of express, jwt and dotenv. After that we are using the express.json and the dotenv.
Next, we have a POST route with /api/create. Here, we are passing the username to a generateAccessToken() to receive the token and after that sending it back to the client in res.json()
Now, in the generateAccessToken() function, we are using jwt.sign() and taking the username, our TOKEN_SECRET and expiry time to generate the JWT token.
After starting the server in terminal with node app.js, we will open Postman and do a POST request to http://localhost:3000/api/create with the username as JSON and we will receive our unique JWT token.
Formidable is an easy-to-use NPM module, which is used to parse from data, especially when uploading files in an Express JS app. It is very popular and has got nearly half a million downloads on NPM.
We will learn how to use it next. First create a new directory and change it. After that initialize a Node.js app by the npm init -y command. We are also adding the dependencies of express and formidable in it.
Then, create a file index.js in the root directory. Also create an uploads folder in the root directory, in which we are going to store the uploaded files.
Next, we are first importing express and after that the fs (File System) module. We are also importing path modules and formidable.
We are using the app with express and with it creating a POST route using app.post(). Inside the post method, we are taking the data from the incoming form using formidable.
Now, we are parsing the form and adding the incoming file to the uploads folder. We are also reading it using the fs module.
Lastly, we are listening at port 3000 for incoming requests.
Now, go to postman and create a POST request and make a key of profilePic and upload a file and send it.
Now, when we check in the uploads folder the file is uploaded successfully in our server.
We can use Multer to upload files in Express.js applications. It is an easy-to-use package which adds the capabilities to upload single or multiple files through Express.js.
First, we shall create a new directory and change it. After that initialize a Node.js app by the NPM init -y command. We are also adding the dependencies of express and multer in it.
Next, we will create a server.js file and add the below code in it. Here, we are first importing express and multer. After that we are given the destination directory to store the uploaded file.
We have created a POST route to upload a single file using multer, using the upload.single().
Next, we will start the node server by giving node server.js in the command line. After that in Postman, we will go to the /single route and upload a single file and send it. Give the options, as in the screenshot below.
Now, we can see a new uploads folder been created and the file been uploaded in it.
Now, we will create a new endpoint to upload multiple files through upload.array(). Here, we are also giving the max number of files that can be uploaded.
Now, we will send multiple files from Postman to the /bulk route and it will be successful.
The new files are also saved in the uploads folder.
Express app doesn’t follow any defined structure, so sometimes it’s up to the developer or the Architect to create one. But when we don’t follow a structure, it is very difficult to maintain the project at the later stages when it grows.
There are two types of Express projects. One which has the complete frontend and backend built with some templating engine. The other, and more popular one, is to have only RESTful routes built in Express, and a separate frontend which is generally ReactJS, Angular or Vue.
We will look into the structure of a complete web app with express first.
Here, we will have a config folder, which will contain all of our configuration details. It will have a different file for general config, one for credentials and one for database configurations.
After that we will have our models folder which will contain the structure of the different data used in our project.
Next, we will have the routes folder, which contains our different routes used in the project.
We will also have a views folder containing our template files like pug or EJS. These files get converted into actual HTML files during runtime and shown in the client browser.
Finally, we will have the app.js files which is the entry point and connect to everything. We will also have a routes.js file, which is the central routing file and connects to the routes in the routes folder.
The RESTful API design is much simpler and won’t contain the views and public folders, because we are not creating the frontend in it.
We can generate these structures automatically by using any express generator package, while starting the project.
We can use a lot of template engines in express, which are used to change a static file written in server to actual HTML content, to be displayed in the client browser. Some of the popular template engines, which works with express are below -
We will now look into examples of one of the popular template engines, which is EJS. The syntax of EJS is quite similar to HTML code and we can also use dynamic content in it.
First, we will go through the basic setup steps and create a new Node.js application by creating a directory and changing to it. Then will initialize a package.json file with the npm init -y command.
Now, install express and EJS into the node application by using the command npm i express ejs in the terminal.
Next, we will create a file index.js in the root directory and put the below code in it. Here, we are first importing express and then setting it to app. Now, with this app we are using the ejs as our view engine.
After that we are having a get function to /. Inside the get function, we have a variable people first, containing an array of object people. Then we are using the res object to render a home component and passing people array to it.
Lastly, we are listening to all incoming requests are localhost 3000.
Once this is done, we will create a views folder and inside it home.ejs file. Now, in this file we will put an h1 and a p tag with content. Notice the coding style for EJS, is quite similar to that of an HTML code. Inside an ul tag, we are also looping through the people array, which we got from index.js and printing the name in li tags.
Now, just go to http://localhost:3000/ and we will get the EJS file rendered as html on the browser.
It is very important to make the cookie secure or else it can be misused for cross-scripting attacks. For example, you can access the cookie which is stored in the browser by using the document.cookie command from the console.
There are several attributes available, while setting the cookie which generally make it more secure. Let's take a look at them with an example.
First, create a project directory and go to it. After that initialize a node project by giving the command npm init -y from the terminal.
After that we will install express and cookie-parser in the project.
Now, create a server.js file in the same directory and add the below code in it. We are using res.cookie() here to send the cookie information to the client. But notice that we are also sending a third parameter which contains some parameters. Now, these means the following:
Now, in the browser go to http://localhost:3000/ and we will see the message Cookie Saved Successfully. After that, open the developer tools and Go to Storage and then expand Cookies and we will see the cookie being saved with Security values.
There are many situations in which we want to delete cookies from the client browser. There can be situations, where we are told to delete cookies once the user logs out from the applications. We will look into an example to understand the same.
First create a project directory and go to it. After that initialize a node project by giving the command npm init -y from the terminal. We also need to install express and cookie parser in the project.
Now, create a file server.js and add the below content in it. Here, we have a root route which stores the user information in a cookie named login info. Now, we have a /logout route and when the user navigates to it, the cookie login info is cleared, through the res.clear cookie function. We are passing the name of the cookie to be cleared, which is login info.
Now, we will go to http://localhost:3000/ and we will see the message Cookie Saved Successfully. Now in the developer tools open Storage and then expand Cookies and we will see the cookie being saved.
Next, go to the route http://localhost:3000/logout and you will see the message Cookie loginInfo cleared and also in the Storage tab, there is no cookie information.
First, we will have our Node runtime installed and created using npm init -y. We will also install express in our Node.js app.
After that, we will create a public folder and an index.html file in it and put the simple content in it.
Next, we will create a style.css file in the public folder. Here we are giving the styles for a beautiful gradient background..
Now, create a main.js file in the public folder. Here, we had put the code for a simple alert.
Then, we will create the server.js file and import the path and express. After that we are using app.use and inside it using path, which is required to generate static paths and serve static assets.
And lastly, we are serving the index.html file through the sendFile.
Now, start the server by giving the node server.js in the terminal. When we go to http://localhost:8080/ and we will see this beautiful webpage with the alert.
Express.js is a powerful and widely used web development framework built on Node.js. It simplifies the process of building web applications, making it an essential tool for developers. Job interviews for web development positions may include questions on Express.js, making it important for candidates to be well-versed in the framework and its implementation.
Express.js interview questions can range from basic to advanced, covering topics such as routing, middleware, templates, and error handling. Answering these questions confidently and accurately can demonstrate a candidate's proficiency in web development using Express.js and set them apart from other applicants.
Furthermore, continuous learning and practice are crucial for mastering Express.js and staying up-to-date with new frameworks and technologies. Reviewing common Express.js interview questions can help developers prepare for job interviews and improve their chances of landing a job in the web development field.
ExpressJS is built on top of NodeJS and can be used as backend API interface building. You can opt for full stack developer training course to master full stack development.
In summary, mastering Express.js is essential for a successful career in web development, and reviewing common interview questions can help developers showcase their skills and knowledge.
You can also refer to KnowledgeHut’s web design course that can improve your front-end skills.