MIDDLEWARE IN nodejs |nodejs tutorials

 

midleware before responding to actual request middleware responds 

in below middleware , we wil not pass params, it willl get automaticlly


const logger =(req,res,next)=>{}

const logger =()=>{

const method = req.method

const url = req.url

const time = new Date().getFullYear()

console.log(method,url,time)

next()

}


app.get('/'. logger, ()=>{})


app.get('/',logger, (req,res)=>{

res.send('HOME');

})


 




write that loggger in seperate page

logger.js

const logger = ()=>{}

module.exports = logger

import taht logger 

const logger = require('./logger');

use taht logger as middleware


app.get('/name',logger)
app.get('/name2',logger)

instead of using in all paths we can use app.use
app.use(logger)

app.get('/name')
app.get('/name2')

j

how to use multuiple middlewares

Authorize middleware

const authorize = (req,res,next) => 
{
console.log('authorize')
next()
}

impor this authorize middleare

app.use([authorize,logger])


get the id from name using authorize middleware



multiple middlwares for single api

app.get('/',[logger,authorize], (req,res)=>{

res.send('HOME');

})


morgan

npm i morgan

it logs for every http request 

require('morgan')

app.use(mogan('tiny'));



it brings from public folder

app.use(express.static(''./public));

 app.use(express.static(''./methods-public));

 if in this folder it has any  files taht wil reflect ist

like login page


previously we imported individual pages like script, css, index but now we use one folder directly 

so because of this it will will call after page loads

means login must for any page

get data into required file using api 


after click submit do axios post



https://github.com/john-smilga/node-express-course/blob/main/02-express-tutorial/methods-public/javascript.html

in request data there , if not there



























No comments:

Post a Comment

server laravel application

 asset_url = domain/public chmod -R 755 public/admin/ composer dump-autoload get the application from hostinger