如何将express api限制为只允许来自客户端的post请求



我正在开发我的第一个全栈应用程序,特别是MERN堆栈,遇到了一些问题。我正试图在我的网站上实现一个存储在数据库中的团结游戏排行榜。我已经做好了一切工作,客户可以使用我的Expressapi从我的MongoDB Atlas数据库中发布和获取分数。然而,在排行榜的情况下,我需要确保分数只能由客户根据游戏的进展情况发送。在目前的工作配置下,任何人都可以通过api发送欺骗分数,而无需玩游戏。

我最初的想法是尝试实现JWT来验证api调用是否来自网站,但在我的脑海中,任何像JWT这样的身份验证令牌仍然可以被用户复制下来,并通过Postman轻松地发送伪造的分数。

我对数据库不太熟悉,我怀疑如果我没有使用Atlas这样的DBaaS提供商,这可能会得到解决,但我不完全确定。

如有任何想法或建议,我们将不胜感激!

您可以定义一个中间件函数并检查传入请求的方法:

const allowOnlyPost = (req, res, next) => {
if (req.method !== 'POST') {
return res.status(401).send(`Method ${req.method} not allowed`)
}
next()
}
module.exports = { allowOnlyPost }

然后将其应用于您想要保护的路线:

const { allowOnlyPost } = require('./your/middleware/folder')
app.use('/route/to/protect', allowOnlyPost, (req, res) => { ... })

对当前答案功能的改进可以是:

const allowMethods = (...methods) => { 
return (req, res, next) => {
if (!methods.map(m => m.toUpperCase()).includes(req.method.toUpperCase())) {
return res.status(401).send(`Method ${req.method} not allowed`)
}
next()
}
}
module.exports = { allowMethods }

所以你可以这样使用它:

const { allowMethods } = require('./your/middleware/folder')
app.use('/route/to/protect', allowMethods('get','post'), (req, res) => { ... })

最新更新