Joi.js表单验证-以json的形式返回消息

时间:2018-08-23 20:13:18

标签: javascript node.js validation express joi

我正在使用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>{&quot;status&quot;:400,&quot;statusText&quot;:&quot;Bad Request&quot;,&quot;errors&quot;:[{&quot;field&quot;:[&quot;emailOrUsername&quot;],&quot;location&quot;:&quot;body&quot;,&quot;messages&quot;:[&quot;\&quot;emailOrUsername\&quot; is not allowed to be empty&quot;],&quot;types&quot;:[&quot;any.empty&quot;]},{&quot;field&quot;:[&quot;password&quot;],&quot;location&quot;:&quot;body&quot;,&quot;messages&quot;:[&quot;\&quot;password\&quot; is not allowed to be empty&quot;],&quot;types&quot;:[&quot;any.empty&quot;]}]}</pre>
    </body>
</html>

1 个答案:

答案 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);
});