Today my server is ready to receive requests with json objects
I use app.use(express.json())
But if I try to send a request with any other type of data, my server crashes. I need to prevent this. How to solve this?
SERVER CODE
let app = express();
app.use(cors({
origin: config.corsOrigin,
methods: ['GET', 'POST', 'DELETE', 'UPDATE', 'PUT', 'PATCH'],
preflightContinue: true,
maxAge: 86400
}));
//Server crushes here if i send any other data types
app.use(express.json({
inflate: true,
limit: '100kb',
reviver: null,
strict: true,
type: 'application/json',
verify: (req, res, buf, encoding) => {
if(!req.is('application/json')){
res.json({'error':'Invalid request'});
}
}
}));
//Server go down too
app.use(function(err, req, res, next) {
if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
console.error('Bad JSON');
res.status(500).send('JSON parse error');
}
next(err);
});
app.use(express.urlencoded({ extended: true }));
app.use(router);
new GameService(new HttpsService(app));
I need to ensure that the server doesn't stop when the other data type is sent to the server.
CodePudding user response:
You could try a custom middleware and put it in just the routes you want to validate:
const jsonParserMiddleware = async(req, res, next) => {
if (req.body && typeof req.body === 'string') {
try {
JSON.parse(req.body);
next();
} catch (e) {
res.sendStatus(400).json({ msg: 'Invalid data.' });
}
} else {
next();
}
};
app.get('/', jsonParserMiddleware, async (req, res) => {
const { data } = req.body;
const someResponseData = await myFunc(data)
return res.send(someResponseData);
});
Or you could stick with app.use
, which will perform the validation for all routes:
const jsonParserMiddleware = async(req, res, next) => {
if (req.body && typeof req.body === 'string') {
try {
JSON.parse(req.body);
next();
} catch (e) {
res.sendStatus(400).json({ msg: 'Invalid data.' });
}
} else {
next();
}
};
app.use(jsonParserMiddleware);
P.S: As far as I know, the first argument of a middleware will always be the Request
object. Why are you trying to get some kind of error?
CodePudding user response:
You can update verify
option to verify body json content.
verify: (req, res, buf, encoding) => {
if(!req.is('application/json')){
throw new Error('Invalid request');
}
try {
JSON.parse(buf.toString(encoding)); // try to parse the body buff
} catch (err) {
throw new Error('Body is not a json object');
}
}