I'm using express-validation and Joi packages for validating forms on serverside and whenever an error occurs it returns and html page as a response, is it possible to just return a json object?
Route file:
// Validator configuration
const validate = require('express-validation');
const validation = require('../validation/index');
.
.
.
router.post('/login', validate(validation.login), (req, res) => {
// Rest of code
Login validation file:
const joi = require('joi');
module.exports = {
body: {
emailOrUsername: joi.string().required(),
password: joi.string().required()
}
};
and it returns this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>{"status":400,"statusText":"Bad Request","errors":[{"field":["emailOrUsername"],"location":"body","messages":["\"emailOrUsername\" is not allowed to be empty"],"types":["any.empty"]},{"field":["password"],"location":"body","messages":["\"password\" is not allowed to be empty"],"types":["any.empty"]}]}</pre>
</body>
</html>
Yes, it is possible - just use simple middleware:
app.use((err, req, res, next) => {
return res.status(err.status).json(err)
});
Check doc - it says:
error handler is required as of 0.3.0, example:
// error handler, required as of 0.3.0
app.use(function(err, req, res, next){
res.status(400).json(err);
});