Jagora zuwa Routing da Middleware ciki Express

Routing kuma middleware mahimman ra'ayoyi guda biyu ne a cikin Node.js da Express tsarin gina aikace-aikacen yanar gizo.

Routing:

  • Routing shine tsari na ƙayyade yadda za a rike buƙatun daga abokin ciniki da amsa tare da albarkatu masu dacewa akan sabar.
  • A cikin Express, za mu iya ayyana hanyoyi ta hanyar tantance hanyar HTTP(GET, POST, PUT, DELETE, da dai sauransu) da kuma hanyar URL daidai.
  • Kowace hanya tana iya samun ayyuka ɗaya ko fiye don aiwatar da ayyuka kamar sarrafa buƙatun, samun damar bayanai, da aika martani ga abokin ciniki.

Middleware:

  • Middleware ayyuka ne da ake aiwatarwa a jere kafin buƙatar ta kai ga mai sarrafa hanya ta ƙarshe.
  • Ana amfani da su don yin ayyuka na gama gari da gudanar da ayyuka na tsaka-tsaki kamar tantancewa, shiga, sarrafa kuskure, da sauransu.
  • Middleware za a iya amfani da dukan aikace-aikace ko kayyade don takamaiman hanyoyi.
  • Kowannensu middleware yana karɓar sigogin buƙatun(buƙatun) da amsa(amsa) kuma yana iya aiwatarwa, ƙaddamar da buƙatar zuwa na gaba middleware, ko ƙare aiki ta hanyar aika amsa ga abokin ciniki.

Misali hadawa Routing da Middleware cikin Express:

const express = require('express');  
const app = express();  
  
// Middleware
const loggerMiddleware =(req, res, next) => {  
  console.log('A new request has arrived!');  
  next();  
};  
  
// Apply middleware to the entire application  
app.use(loggerMiddleware);  
  
// Main route  
app.get('/',(req, res) => {  
  res.send('Welcome to the homepage!');  
});  
  
// Another route  
app.get('/about',(req, res) => {  
  res.send('This is the about page!');  
});  
  
// Start the server  
app.listen(3000,() => {  
  console.log('Server is listening on port 3000...');  
});  

A cikin wannan misali, mun ayyana al'ada don shiga kowace sabuwar buƙatun da ke zuwa ga uwar garken. Ana amfani da wannan ga duka aikace-aikacen ta amfani da hanyar. Sa'an nan, mun ayyana hanyoyi guda biyu, ɗaya don babban shafi( ) da kuma wani don game da shafi( ). A ƙarshe, mun fara uwar garken kuma mu saurari tashar 3000. middleware loggerMiddleware middleware app.use() '/' '/about'

Za a aiwatar da saƙon ga kowane buƙatu, shigar da saƙo zuwa na'ura mai ba da hanya tsakanin hanyoyin sadarwa kafin aika buƙatun zuwa ga mai sarrafa hanyar daidai ko a cikin jerin. middleware loggerMiddleware middleware

Wannan haɗin kai routing da middleware ba mu damar sarrafa buƙatun daban-daban da yin ayyuka na gama gari da kyau a cikin Express aikace-aikace.