繁体   English   中英

Joi.js 表单验证 - 将消息作为 json 返回

[英]Joi.js form validation - returning messages as json

我正在使用 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>

是的,有可能-只需使用简单的中间件即可:

app.use((err, req, res, next) => {
  return res.status(err.status).json(err)
});

检查文档 -它说:

从0.3.0开始需要错误处理程序,例如:

// error handler, required as of 0.3.0
app.use(function(err, req, res, next){
  res.status(400).json(err);
});
app.use((err, req, res, next) => {
  return res.status(err.status).json(err)
});

在我的情况下,上面的代码不起作用。 我正在使用中间件,但它仍然不起作用。 最后,当我将上面的代码放在app.listen块正上方的最后一个位置时,它app.listen

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM