我正在使用express-validation和Joi包在服务器端验证表单,并且每当发生错误时,它就会返回并以html页面作为响应,是否有可能只返回一个json对象?
路由文件:
// Validator configuration
const validate = require('express-validation');
const validation = require('../validation/index');
.
.
.
router.post('/login', validate(validation.login), (req, res) => {
// Rest of code
登录验证文件:
const joi = require('joi');
module.exports = {
body: {
emailOrUsername: joi.string().required(),
password: joi.string().required()
}
};
并返回以下内容:
<!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>
答案 0 :(得分:3)
是的,有可能-只需使用简单的中间件即可:
app.use((err, req, res, next) => {
return res.status(err.status).json(err)
});
检查doc-它说:
从0.3.0开始,错误处理程序是必需的,例如:
// error handler, required as of 0.3.0
app.use(function(err, req, res, next){
res.status(400).json(err);
});