【问题标题】:Post request isn't working in node.js express/mongoose发布请求在 node.js express/mongoose 中不起作用
【发布时间】:2021-06-20 18:59:06
【问题描述】:

我有一个创建类别的路线,当我尝试在邮递员中运行它时,它返回一条错误消息“无法发布 /api/category”

我试图一遍又一遍地运行我的代码,但我看不出问题出在哪里。 提前感谢您的帮助

我的架构:

const mongoose = require("mongoose");

const CategorySchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "user",
  },
  categoryName: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = Categories = mongoose.model("category", CategorySchema);

我的路线:

const express = require("express");
const router = express.Router();
const auth = require("../../middleware/auth");
const { check, validationResult } = require("express-validator");

const Category = require("../../models/Category");



// @route     POST api/category
// @desc      Create or update users category
// @access    Private
router.post(
  "/",
  [auth, [check("categoryName", "Category name is required").not().isEmpty()]],
  async (req, res) => {
    console.log(categoryName);
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
  }
);


module.exports = router;

this is the way my code is organized

【问题讨论】:

  • 我在您的代码中没有看到任何 POST 路由 /api/category。您能说明如何将路由器添加到主快递应用程序吗?
  • 感谢您与我们联系,我已经编辑了我的帖子。
  • 它应该是 /api/category 而不是 / 在你的路线
  • 好的,让我再试一次。您能否显示 server.js 中的代码,特别是将您从 routes/api/category.js 导出的路由器添加到主 express 应用程序的部分?我期待像app.use('/api/category', ..)这样的东西
  • 感谢 Molda,这是问题所在。我错过了 server.js 文件中的路由

标签: node.js express mongoose-schema


【解决方案1】:

好的,感谢 Molda,我找到了问题。

我的 server.js 文件中缺少路由定义。 现在一切顺利,感谢您的帮助。

const express = require("express");
const connectDB = require("./config/db");

const app = express();

//Connect DB
connectDB();

// Init Middleware
app.use(express.json({ extended: false }));

app.get("/", (req, res) => res.send("API Running"));

// Define routes
app.use("/api/users", require("./routes/api/users"));
app.use("/api/auth", require("./routes/api/auth"));
app.use("/api/profile", require("./routes/api/profile"));
app.use("/api/category", require("./routes/api/category"));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

【讨论】:

    猜你喜欢
    • 2014-07-29
    • 2013-03-10
    • 2011-11-23
    • 1970-01-01
    • 2014-06-15
    • 2018-10-06
    • 2013-05-15
    • 2012-12-13
    • 2020-05-31
    相关资源
    最近更新 更多