ExpressJS is a framework that we use to create our server side applications.
Installation
npm install express
Create ‘Hello World’ Express App
First create a file “index.js”
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send("Hello World")
})
app.listen(8000, ()=> {
console.log('connected to backend')
})
Now Start Your APP
node index.js
Note: when running it, make sure you are in the backend folder (go with : cd backend)
Simplify this process with script:
Add this line inside script of package.json
"start":"node index.js"
now write "npm start" to run the server
For Continuously Running the Server
Install Nodemon
npm install nodemon
Now run with:
npx nodemon index.js
Simplify this process with script:
Add this line inside script of package.json
"start":"nodemon index.js"
now write "npm start" to run the server
Basic Routing, POST & DELETE
GET Request
app.get('/', function(req, res){
res.send('This is a get request. I am fetching some data.')
})
POST Request
app.post('/', function(req, res){
res.send('This is a post request. I am sending some data through a registration form.')
})
DELETE Request
Use Case: Suppose you have a list of fruits and you want to delete 2nd fruit.
DELETE http://localhost:3000/fruits/2
// Simple list of fruits with IDs
let fruits = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Mango' }
];
app.delete('/fruits/:id', (req, res) => {
// Get ID from URL
const id = parseInt(req.params.id);
// Remove the fruit with the given ID
fruits = fruits.filter(fruit => fruit.id !== id);
res.send(`Fruit with ID ${id} deleted!`);
});
ROUTES in a DIFFERENT FILE
File: /routes/users.js (For all GET, POST Requests for Users)
var express = require('express')
var router = express.Router()
router.get('/', (req, res) => {
const users = [] // get from db
res.send(users)
})
router.get('/:id', (req, res) => {
const user = {} // get from db
res.send(user)
})
router.post('/', (req, res) => {
const user = req.body // save user to db
res.send({status: 'success'})
})
module.exports = router
ADDING ROUTES FROM: /routes/users.js
app.use('/user', require('./routes/user'));
Middlewares
for middlewares
// Built-in middleware for parsing JSON requests
app.use(express.json());
// Serve static files
app.use(express.static(‘public’));
MySQL Connection
I have explained in this article on how to connect MYSQL with the ExpressJS/NodeJS.