Handlings Route Express.js 我从 try 和 catch 块都得到响应?

问题描述 投票:0回答:1

//服务器.js

const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config({ path: "./config.env" });
const app = require("./app");

mongoose
  .connect(process.env.LOCAL_CONN_STRING, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then((conn) => {
    console.log(`Connection successfull with : ${conn}`);
  })
  .catch((err) => {
    console.log("error is: ", err);
  });

// **************************************
// start the server
app.listen(5000, () => {
  console.log("server has started");
});

// 控制器 `

createCategory = async(req, res) => {
    try {
        const { name } = req.body;
        const category = await Category.create(
            { name },
        {
        new: true,
        runValidators: true,
      }
    );
    res.status(200).json({
        status: "success",
        data: {
            category,
        },
      });
    } catch (err) {
        res.status(404).json({
            status: "fail",
            data: {
                error: err.message,
            },
            });
     }
};

// 验证器是 `

const categorySchema = new mongoose.Schema({
     name: {
         type: String,
         required: [true, "category must be specified"],
         minlength: 10,
         maxlength: 100,
         unique: [true, "Category name must be unique"],
      },
  });

//我从邮递员那里得到的回复在给定的图像中  response i get from postman is in the image given

我期待该文档将被创建,并且它已创建,如您在 mongoDb 指南针中的图像中看到的那样,但我的 catch 块仍然执行,这里出了什么问题帮助?

i was expecting the document will be created, and it is created as you can see in the image in mongoDb compass but my catch block still execute, what is wrong here help?`

express mongoose routes controller try-catch
1个回答
0
投票

您需要添加此行才能解析请求正文。

app.use(express.json());
© www.soinside.com 2019 - 2024. All rights reserved.