Express.js is a framework that is used by millions of developers to create websites. But what is it? How does it work? Why do people use Express over other frameworks?
Express.js is a Node.js framework that is used to create web applications and APIs. it is mainly used to create servers.
Why Use Express?
Before Express.js there was commonJS and ServerJS, two frameworks in which JavaScript developers would use. When Express.js was introduced, it took over frameworks that came before and after such as Fastify or Koa is because it is very beginner friendly, flexible, easy to use, has a built-in middleware framework as well as the fact that it is efficient and has a powerful routing system.
How Do You Use Express?
First, you have to install Express.js in your terminal using Express.js
npm i express
You should have access to Express.js after inputting this in your terminal.
Getting started with server creation using Express.js is fairly simple.
const express = require('express');
//invoke express to create our app
const app = express();
The code above shows how you have to invoke express first in your code.
// Middleware function for logging route requests
const logRoutes = (req, res, next) => {
const time = new Date().toLocaleString();
console.log(`${req.method}: ${req.originalUrl} - ${time}`);
next(); // Passes the request to the next middleware/controller
};
The code block above showcases how you can implement middleware into your server using express
// controllers
const serveHello = (req, res) => {
res.send('Hello guys!')
}
const PORT = 8088
app.listen(PORT, () => {
console.log(`listing at http://localhost:${PORT}`)
})
This code block up above shows how to set up a controller, which is used to send responses to the client.
A port is the endpoint that you are going to send your response to.
"app.listen" is what is used here to let me know if my server is running or not.
All in all, Express.js is simple to use for people who are familiar with JavaScript and want a minimalistic approach for a lightweight application that requires a lot of routing.
Top comments (0)