Express JS 强制请求体类型

3

是否可以声明请求体的类型?如果请求体中包含未声明的属性,我希望返回错误请求。

import express from 'express'

const app = express()

app.use(express.json())

interface CustomRequest extends express.Request{
    body:{
        name:string
    }
}

app.post('/t', (req: CustomRequest, res: express.Response) => {
    res.send("hello world")
})

app.listen(5000, () => {
    console.log("app listening on 5000")
})
1个回答

1
我建议您查看 @hapi/joi 包的网站。https://hapi.dev/module/joi/ 它易于使用且功能强大!
您可以实现一个中间件来验证请求(body,params,query)和响应对象!您可以使用 express-joi-validator 包来完成此操作。
首先,您必须导入模块:
const Joi = require('@hapi/joi');
const joiValidator = require('express-joi-validation')
  .createValidator();

然后定义你的模式(期望的对象结构)

const loginSchema = Joi.object({
    user: Joi.string().required(),
    password: Joi.string().required(),
});

最后实现你的中间件:
app.post('/login', joiValidator.body(loginSchema), (req, res) => {
    // Your logic here...
    res.send({status: 'ok'}); // Just an example
});

如果验证失败,服务器会发送一个400(错误请求)响应给客户端!
如果您有任何疑问,请告诉我!
希望能对您有所帮助!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接