首页 > 解决方案 > 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: &quot;name&quot; length must be at least 3 characters long<br> &nbsp; &nbsp;at C:\Users<br> &nbsp; &nbsp;at processTicksAndRejections (internal/process/task_queues.js:97:5)</pre>
</body>

</html>

标签: node.jsexpressvalidationjoi

解决方案


声明路线后,您能否确认您正在调用 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}`);
});

推荐阅读