【发布时间】:2022-02-10 19:05:04
【问题描述】:
在 Node JS 中处理中间件时,我已经实现了一个代码,如果 age>=18 用户可以访问该网站,否则不能,但是当我输入查询时,例如 localhost:3000/?age=12 它可以工作,但 localhost:3000/ ?age="12" 它不起作用任何人都知道它为什么会发生以及如何解决它
代码:
const express = require('express')
const app = express()
const port = 3000
// middleware
// req,res we need to modify so it is there
// next is a function it will proceed when route is called
const reqFilter=(req,res,next)=>{
console.log('reqFilter');
// we have to call next otherwise it will keep loading in browaer
// eg:-> if age is older then 18 user can access page
if(req.query.age<18){
res.send('Please Confirm You are over 18')
}
else if(!req.query.age){
res.send("please put down age")
}
else{
next();
}
}
// using the middleware
app.use(reqFilter)
app.get('/', (req, res) => {
res.send("welcome to homepage")
})
app.get('/users', (req, res) => {
res.send("welcome to users page")
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
【问题讨论】:
标签: node.js express middleware