【问题标题】:Celebrate/Joi returns in case of error HTML instead of JSONCelebrate/Joi 在错误的情况下返回 HTML 而不是 JSON
【发布时间】:2020-07-01 15:23:06
【问题描述】:

目前我已经在我的 Node/Express 服务器上安装了庆祝活动。只要不满足某些验证条件,它就会在 HTML 文件而不是 JSON 对象中接收错误。我正在使用const app = express() 作为记录。如何改为返回 JSON 对象?

server.js

const { errors } = require('celebrate');

app.use(errors());

profile-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);
}
});

validation-schemas.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.js express validation joi


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-03-03
      • 2012-09-24
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多