project structure:-
1. config
2. controller
3. model
4. views
5. public
6. routes
7. index.js
8. package.json
9. package-lock.json
Next Step:- Add dependencies
{
"dependencies":{
"express":"latest",
}
}
Adding Hot Reloading:-
using nodemon :-
local server with autoreloading feature.
nodemon install
- locally
npm install nodemon or
{
"dependencies":{
"express":"latest",
"nodemon": "latest"
}
}
npm install
2. globally
npm install --global nodemon
nodemon.cmd
nodemon.bat
global path.
npx nodemon index.js => server start
.
node nodemon index.js
in order to run using npm :-
locally :-
open package.json
{
"scripts":{
"test": "node test for error",
"start": "node ./node_modules/nodemon/bin/nodemon.js index.js"
}
}
globally :-
open package.json
{
"scripts":{
"test": "node test for error",
"start": "nodemon index.js"
}
}
const express = require('express');
const app = express();
const port = process.env.PORT || '8080';
app.listen(port, ()=>{
console.log(`Server Started on port ${port}`);
})
app.get("/", (req,res)=>{
res.write("Hello world");
res.end();
})
const http= require('http');
const server = http.createServer();
const port = process.env.PORT || '8080';
server.listen(port, ()=>{
console.log(`Server Started on port ${port}`);
})
const express = require('express');
const app = express();
module.exports = app;
const http= require('http');
const app = require('./app');
const server = http.createServer(app);
const port = process.env.PORT || '8080';
server.listen(port, ()=>{
console.log(`Server Started on port ${port}`);
})
All EndPoints, in Api and url fro get,post,put,patch,delete are managed by, routes.
## by default Route :-
app.get('/xyz-url', (req,res)=>{
res.send('get-url');
});
app.post('/xyz-url', (req,res)=>{
res.send('post-url');
});
express has inbuilt router.
crud : studentRoute.js
get
post
put
delete
crud : userRoutes.js
get => All user
post
put
delete
login => post + get
userVerification => user
forgetPassword => user
const router = express.Router();
router.get('/xyz-url', (req,res)=>{
res.send('get-url');
});
router.post('/xyz-url', (req,res)=>{
res.send('post-url');
});
module.export = router;
- app.js connect with router.
const studentRoute = require('./studentRoute');
const userRoute = require('./userRoute');
app.use('/student',studentRoute);
app.use('/users',userRoute);
consider the code of routes
Before controller :-
router.post('/xyz-url',(req,res,next)=>{
res.send('post url');
});
After controller :-
StudentController.js
//class level code
or
//function level (next middleware or next closure can be used as callback)
|
|
const Student = {
getStudent: function(req,res,next){
//logic
}
CreateStudent:function(req,res,next){
//logic
}
UpdateStudent:function(req,res,next){
//logic
}
DeleteStudent:function(req,res,next){
//logic
}
}
module.export = Student;
const StudentController = require('./StudentController');
router.get('/student-list',StudentController.getStudent);
router.post('/register',StudentController.createStudent);
router.put('/change-profile',StudentController.UpdateStudent);
router.delete('/delete-account',StudentController.DeleteStudent);
npm ---> package.json ---> start ----> nodemon (not required in live server)---> index.js
index.js---> config ----> app.js ----> use Middleware -----> router -----> controller
till now we are able to create, index,app,routes and controller in the Node Application.
But our Node Application may require static pages to be created.
for this we can make a pages or static folder in project
project structure :-
- config
- controller
- model
- views
- public
- routes
- index.js
- package.json
- package-lock.json
- pages <----------------------- This is pages folder (or static) | ------------> index.html | ------------> about.html | ------------> contact.html | ------------> register.html ...... .....n here we can make static folder name also. Note :: All the pages will be loaded in GET Request.
const path = require('path');
router.get("/home",(req,res,next)=>{
let home_page = path.join(__dirname, "./pages/home.html")
res.sendFile(home_page)
})
fallback : fallback when responce is ended without, expectation.
error.html
or
404.html
<h1>404 page Not Found</h1>
app.use('*',function(req,res,next){
let pagename = path.join(__dirname, "./pages/404.html")
res.sendFile(pagename)
})
controller :- It seperated Business logic from the Application.
it acts as middle man, B/w Model and View.
Controller takes the data from model and return to view.
and vice-versa.
three ways of writing the controller
1. Normal Functions or Anonymous function to reference.
2. Factory Function or Factory Object.(Function as Object)
3. using classes or TypeScript.
router,get('/home',HomeController.create());
|
|
|
import/require
|
|---->package.json ---> "type":"module" or rename : .js to .mjs
|
|
|------> require ---> const HomeController = require('../Controller/HomeController')
|
|
|
module.exports = create;
function create(req,res,next){
// business logic
}
const Student :{
create: (req,res,next)=>{
// logic
next()
}
update: (req,res,next)=>{
// logic
next()
}
delete: (req,res,next)=>{
// logic
next()
}
}
// How to call:-
Student.create();
// How to export :-
module.exports = Student;
class StudentController
{
constructor(){}
home(req, res, next)
{
// logic
}
create(req, res, next)
{
// logic
}
show(req, res, next)
{
// logic
}
}
// How to export:-
module.exports = StudentController;
// How to import and use:-
const StudentController = require("../controller/StudentController.js");
router.get('/', (req, res, next) =>
{
new StudentController().home(req, res, next);
})
router.get('/create', (req, res, next) =>
{
new StudentController().create(req, res, next);
})
router.get('/show', (req, res, next) =>
{
new StudentController().show(req, res, next)
})
// other ways
// ------------
const student = new StudentController();
router.get('/', (req, res, next) =>
{
student.home(req, res, next);
})
router.get('/create', (req, res, next) =>
{
student.create(req, res, next);
})
router.get('/show', (req, res, next) =>
{
student.show(req, res, next)
})