node.js - Celebrate/Joi 在错误的情况下返回 HTML 而不是 JSON
问题描述
目前我已经在我的 Node/Express 服务器上安装了庆祝。只要不满足某些验证条件,它就会在 HTML 文件而不是 JSON 对象中接收错误。我正在使用const app = express()
记录的。如何改为返回 JSON 对象?
服务器.js
const { errors } = require('celebrate');
app.use(errors());
配置文件-route.js
router.post('/', [auth, celebrate({ body: Validate.profileSchema })], async (req, res) => {
const {
name,
} = req.body;
try {
let profile = await Profile.findOne({ user: req.user.id });
if (profile) {
profile = await Profile.findOneAndUpdate({ user: req.user.id }, { $set: profileFields }, { new: true });
return res.json(profile);
}
profile = new Profile(profileFields);
await profile.save();
res.json(profile);
} catch (error) {
res.status(404).json(error.message);
}
});
验证模式.js
const profileSchema = Joi.object().keys({
name: Joi.string().min(3).max(30).required(),
});
输出
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error: "name" length must be at least 3 characters long<br> at C:\Users<br> at processTicksAndRejections (internal/process/task_queues.js:97:5)</pre>
</body>
</html>
解决方案
声明路线后,您能否确认您正在调用 app.use(errors()) 。
import express from "express";
import bodyParser from "body-parser";
import { Joi, celebrate, errors } from "celebrate";
const PORT = process.env.PORT || 3000;
const app = express();
app.use(bodyParser.json());
const schema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().required(),
}).required();
app.post("/session", celebrate({ body: schema }), (req, res) => {
const { email, password } = req.body;
const { token } = login(email, password);
res.status(201).send({ token });
});
app.use(errors()); // <--- Should be here
app.listen(PORT, () => {
console.log(`Server listens on port: ${PORT}`);
});
推荐阅读
- python - Python - 离线获取两个地址之间的最短路线
- entity-framework-core - 使用 MVC2 DI 和迁移遗留系统的建议
- java - 在无效 JSON 的情况下抛出有意义的响应
- python - 在 PostgreSQL 11.0 表中插入数据时出现 TypeError
- c++ - 关于指针和动态内存的一般问题
- java - 如何使用 mockito 测试运行异步线程的方法
- python - 如何在给定索引的情况下仅循环列表的一部分
- excel - 如何在excel中转换这个数据集?
- symfony5 - Shopware 5 Api - 套接字挂断
- typescript - 包装器
或包装器 >?