Express is a backend Framework which makes our job easier by providing us with most of the things that we need to quite often so we can use them rather than creating them again and again.
for example
- Authentication
- Setting up a server
- Requests to other API’s
Setting up a Basic server with Express
Here is the code to set up a basic server with the help of Express
//Import Express
const express = require('express')
//Create an app instance with express
const app = express()
//Create a route for incoming requests
//(path. callback to respond)
app.get('/', (req, res) => res.send("Hello world"))
//Usually the port is defined in the Environment variables
//const PORT = process.env.PORT || 3000
const PORT = 3000
//Now the app is listening for requests for the defined PORT
app.listen(PORT, () =>{
console.log('Now listening on PORT 3000')
})
If we make any changes we will have to restart the server again and again to avoid that we use the watch flag offered by node
So to run the app use:
node --watch app.js
Here is an example of a very basic Routing APP
Here is an example of a very basic routing APP, which takes the HTML views from the folder views.
const express = require("express");
const path = require("path");
const app = express();
app.get("/", (req, res) =>
res.sendFile(path.join(__dirname, "views/index.html"))
);
app.get("/aboutme", (req, res) => {
res.sendFile(path.join(__dirname, "views/about.html"));
});
app.get("/contact-me", (req, res) => {
res.sendFile(path.join(__dirname, "views/contact-me.html"));
});
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "views/404.html"));
});
app.listen(3000, () => {
console.log("The App is listening on PORT 3000 now. ");
console.log(__dirname);
});
Author Of article : Tushar Tushar Read full article