【问题标题】:why localhost:3000/?age=12 works but localhost:3000/?age="12" doesn't in Express Node JS为什么 localhost:3000/?age=12 有效但 localhost:3000/?age="12" 在 Express Node JS 中无效
【发布时间】: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


    【解决方案1】:

    来自快递文档:https://expressjs.com/en/api.html

    As req.query’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.query.foo.toString() may fail in multiple ways, for example, foo may not be there or may not be a string, and toString may not be a function and instead of a string or other user-input.
    

    您将查询参数与数字18进行比较,您需要检查查询的类型。您可以使用if (typeof req.query.age == 'string') 执行此操作,也可以将“18”转换为数字。 您可以通过添加 + 来做到这一点:+req.query.age

    【讨论】:

    • 感谢您的回复,手工类型检查在制作生产级网站时留下了很多漏洞。有没有其他方法可以对输入的每个查询进行类型检查?
    猜你喜欢
    • 2014-05-13
    • 2021-11-02
    • 2021-11-24
    • 2017-03-03
    • 1970-01-01
    • 2020-05-21
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多