Express is a backend framework that is built on Node Js which allows you to make API calls, determine the route and create dynamic pages easily. It provides various utilities that make creating a backend service with Node Js a lot easier.
As a backend service, Express can be used to create HTTP Servers, REST APIs, Configure Routing, apply middleware to routes, and a lot more.
Creating a backend service with Node Js alone can be hectic and involves a whole lot of code writing, with Express, the job is a lot easier and user-friendly. Express complement Node Js.
INSTALLING EXPRESS
Before we can use Express on our project, we need to first install the application. You can do that by running the code below.
npm install express --save
RUNNING A SERVER WITH EXPRESS
To create a server and listen to requests using Express, head on to your code editor and create a new javascript file, then run the code below;
const express = require('express');
const app = express();
app.listen(3000, () => console.log('App is listening on port 3000.'));
In the code above, we 'require' the express package into our project and initialize it on the app variable, then, we call the listen method on the app, specifying the port we want to listen request on, which in our case is port 3000.
HANDLING ROUTING REQUESTS ON EXPRESS
app.get('/', (req, res) => {
try {
return res.status(200).send('Hello World');
} catch(err) {
console.log(err);
return res.status(400).send(err.message);
}
});
In the code above we are handling a GET request to the homepage denoted with the "/", if the request is successful, we send a status code 200 which indicates it is a successful request and the message "Hello World" is printed on the homepage. However, if the request is bad, we catch the error, printing it to the console as well as sending the error message to the homepage. In this particular code, we made use of the try-and-catch method to handle errors.
MAKING USE OF MIDDLEWARES IN EXPRESS.
Middleware is something that happens between when a request is made and when the response gets sent. It's like a middleman. They're various built-in middlewares and third-party middlewares created to make handling requests and responses a lot easier with Express.
One built-in middleware you will be using a lot in Express is the Router middleware. This is used when you want to create a new router object to handle your requests in your application.
const express = require('express');
const app = express();
//we initialize the router method on a variable called router
const router = express.Router();
router.get('/user', function (req, res, next) {
console.log("Router Working");
res.status(200).send('Welcome to the User page');
})
app.use(router);
app.listen(3000, function (err) {
if (err) console.log(err);
console.log("Server listening on port", 3000);
});
In the code above we initialize the new router object, then handle our request, and make use of the middleware using "app. use()", then listen to our server. Note that to make use of middleware using express we have to call the use method on the app, passing in the middleware.
Another vital middleware we will be using a lot in Express is the express.json() middleware. It comes in handy when handling "POST" requests. It parses the incoming request with JSON payloads and is based on a body parser.
const express = require('express');
const app = express();
//we initialize the middleware using the app.use method
app.use(express.json());
app.post('/', function (req, res) {
console.log(req.body.name)
res.status(200).send(req.body.name);
})
app.listen(3000, function (err) {
if (err) console.log(err);
console.log("Server listening on PORT", 3000);
});
Finally, let's look at a third-party middleware we can use to make working with Express a lot better. Here, we look at the morgan middleware. We use Morgan to log additional information concerning the request we are receiving. It provides info on the type of req, the status code and any other information that may be stipulated. Morgan helps make debugging our code a lot easier.
To use Morgan, we have to first install it in our project.
npm install morgan
Then run the code below;
const express = require('express');
const morgan = require('morgan');
const app = express();
// Use Morgan middleware
app.use(morgan('dev'));
// Define your routes and other middleware here...
app.get('/', (req, res) => {
try {
return res.status(200).send('Hello World');
} catch(err) {
console.log(err);
return res.status(400).send(err.message);
}
});
// Start the server
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
In the code above, after installing the Morgan package, we then require it in our application, then, we use the app.use() method again the apply the Morgan middleware to all our routes. So, whenever any route is called, we get information concerning the route and log it to the console. This like I said earlier, helps in debugging.
With this, we have come to the end of this post on Express. To read more on Express, head to the documentation on their website by clicking here.