Middleware
- Implementing a middleware is very simple, for example:
my-nodestack-app
├── src
│ ├── middleware
│ │ │ │── example.js
│ ├── routes
│ │ │── middleware
│ │ │ │── index.js
├── ndsk.config.js
└── package.json
module.exports = {
name:"example", // middleware name
handler:async (request,h)=>{
const id = request.query.id;
if(id === '1'){
h.next({name:"this is example moddleware"});
}else if(id === '2'){
return 'end---'
}else{
return h.redirect('https://ndsk.dev');
}
}
}
export const options = {
plugins:{
middleware:{
example:true
}
}
};
export default (request)=>{
return request.middleware.example
}
-
We created the
src/middleware/example.js
middleware file and named the current middleware as:example
. In theroutes/middleware/index.js
route, setmiddleware.example:true
to enable the current middleware and userequest.middleware.example
to get the value returned by the current middleware -
If
request.query.id
is equal to 1, returnh.next(value)
to continue to the next step. Ifrequest.query.id
is equal to 2, directlyreturn
to end the current request. Ifrequest.query.id
is equal to , redirect to'https://ndsk.dev
To enable middleware you need to configure example:true
in the route
export const options = {
plugins:{
middleware:{
example:true //Middleware Name
}
}
};
- You can use
request.route.settings.plugins.middleware
to get the middleware configuration - Middleware can only handle business logic when requesting and responding