Joi.js 表单验证 - 将消息返回为 json
Joi.js form validation - returning messages as json
我正在使用 express-validation 和 Joi 包在服务器端验证表单,每当发生错误时,它 returns 和 html 页面作为响应,是否可以 return一个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()
}
};
它 return 是这样的:
<!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>
是的,这是可能的 - 只需使用简单的中间件:
app.use((err, req, res, next) => {
return res.status(err.status).json(err)
});
检查 doc - 它说:
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);
});
app.use((err, req, res, next) => {
return res.status(err.status).json(err)
});
在我的例子中,上面的代码不起作用。我正在使用中间件仍然没有用。当我将上面的代码放在 app.listen
块
正上方的最后一个位置时,它终于起作用了
我正在使用 express-validation 和 Joi 包在服务器端验证表单,每当发生错误时,它 returns 和 html 页面作为响应,是否可以 return一个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()
}
};
它 return 是这样的:
<!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>
是的,这是可能的 - 只需使用简单的中间件:
app.use((err, req, res, next) => {
return res.status(err.status).json(err)
});
检查 doc - 它说:
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);
});
app.use((err, req, res, next) => {
return res.status(err.status).json(err)
});
在我的例子中,上面的代码不起作用。我正在使用中间件仍然没有用。当我将上面的代码放在 app.listen
块