is it possible to declare the types for the request body? I want to return bad request if the body contains other properties than the declared ones
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")
})
I suggest you to take a look at @hapi/joi package web site. https://hapi.dev/module/joi/
It's easy to use and very powerful!
You can implement a middleware to validate the request (body, params, query) and also response objects! You can do it using the express-joi-validator package.
First you must import the modules:
const Joi = require('@hapi/joi');
const joiValidator = require('express-joi-validation')
.createValidator();
Then define your schema (expected object structure)
const loginSchema = Joi.object({
user: Joi.string().required(),
password: Joi.string().required(),
});
Finally implement your middleware:
app.post('/login', joiValidator.body(loginSchema), (req, res) => {
// Your logic here...
res.send({status: 'ok'}); // Just an example
});
If validation fails it will send back to client a 400 (Bad Request) response!
Let me know if you have any question about it!
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With