Hola coders 👩💻
In this article, we are getting started with backend development using Nodejs and ExpressJS. We will build a getting started the app and listen to the request on the server.
Tools Required
Nodejs
VS Code
Postman
Types of Web Request
GET: To request the information from the server
POST: To share the information with the server
PUT: To update the information in the Database
DELETE: To remove the data from the Database
Response Status Codes
These are the codes that provide a special meaning to the user. Everyone is aware of the 404 status code when one makes a bad request. Status codes lie between 100 - 599.
100 - 199: Informational Status Code
200 - 299: Success Status Code
300 - 399: Redirection Status Code
400 - 499: Client Error Status Code
500 - 599: Server Error Status Code
ExpressJS
It is an unopinionated (does not have rules) web framework of Nodejs. It is the heart of the MERN backend that helps in the creation of routes, controllers, and models.
nodeJS should be successfully installed in the system
Execute npm init to get started with the backend. It will ask couple of questions that need to be added or to have default configuration you can execute npm init -y
Install express and nodemon. Execute the following command in the command prompt👇
npm i express nodemon
nodemon is an npm package that detects any change made in the backend and loads the server.
Add the below line of code in package.json under the scripts object.
"start": "nodemon index.js",
GET Request
Create index.js file that will contain the backend code. In line 5 we mentioned nodemon index.js, which is the reason for creating the index.js file.
// importing express
const express = require("express")
//creating instance of express
const app = express()
// port on which server will get executed
const PORT = 5000
//GET Request
app.get("/" , (req , res) => {
const res_json = {
success : "Successfully created a GET request",
page : "Home Page"
}
res.status(200).json({res_json})
})
// Listening the server
app.listen(PORT, () => {
console.log("DU")
})
In app.get(), we pass the route ("/" means home route) and a callback function that contains the request and response.
When home route (localhost:5000) is requested then response returns the status code and a json
Execution steps:
Run the server by executing npm start command
We can hit GET request on the browser by requesting URL:
localhost:5000
Passing parameter in the URL Query
//Passing Parameters
app.get("/api/:token", (req , res) => {
//req.params hold all the parameters
res.status(200).json({params: req.params.token})
})
Execute following URL to access above route http://localhost:5000/api/random_token
The End
I hope you enjoyed the article and had a good learning experience.
Follow for more articles and keep sharing👩
Keep coding👩💻