繁体   English   中英

JSON POST 在 Node/Mongo 上请求空响应

[英]JSON POST requests empty response on Node/Mongo

编辑:我解决了。 这很简单,我在为 body-parser 设置 app.use 之前已经导入了路由,所以它不知道解析 JSON 的热度,因此返回了一个未定义的主体。

我正在尝试按照教程制作 REST API。 我完全按照它所做的去做,并尝试了我能想到的所有修复,但我无法使 JSON POST 请求工作。 发送请求后,我应该得到这样的 JSON:

{
  "_id": "a13d1s2bc12as3a2",
  "name": "Name",
  "desc": "bla bla",
  "_v": 0
}

但相反,我只得到了一个空体的 201 资源。 甚至不是一个空的对象,只是什么都没有。

  • 我在 Postman 和 HTTPie 中尝试了所有可能的配置。
  • 我还尝试了更改 body-parser 配置的建议修复程序,因为我知道在过去几个月中某些内容被弃用或更改(json、urlencoded 等)
  • 我检查 Mongoose 是否使用它用于检查它的功能连接到数据库(它是)。

我不知道问题出在哪里。

这是索引:

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const meals = require("./routes/meals");
const orders = require("./routes/orders");
const app = express();

mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });

app.use("/meals", meals);
app.use("/orders", orders);

app.use(express.json());
app.use(bodyParser.json({ type: 'application/json' }));

module.exports = app;

用餐路线:

const express = require("express");
const Meals = require("../models/Meals");

const router = express.Router();

router.get("/", (req, res) => {
    Meals.find()
    .exec()
    .then(x => res.status(200).send(x));
});

router.get("/:id", (req, res) => {
    Meals.findById(req.params.id)
    .exec()
    .then(x => res.status(200).send(x));

router.post("/", (req, res) => {
    Meals.create(req.body)
    .then(x => res.status(201).send(x));
});

router.put("/:id", (req, res) => {
    Meals.findOneAndUpdate(req.params.id, req.body)
    .then(x => res.sendStatus(204));
});

router.delete("/:id", (req, res) => {
    Meals.findOneAndDelete(req.params.id)
    .exec()
    .then(() => res.sendStatus(204));
});

module.exports = router;

和模型:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const Meals = mongoose.model("Meal", new Schema({
    name: String,
    desc: String
 }));

 module.exports = Meals;

谢谢你。

调试试试这个

const handleError = function() {
    console.error(err);
    // handle your error
};

router.post("/", (req, res) => {

  Meals.create(req.body, function (err, req.body) {
    if (err) return handleError(err);
  })

});

您也可以尝试只提供静态数据进行测试,看看是否有效,例如:

const meal = new Meals({ name: 'some meal',desc: 'some desc' });
meal.save(function (err) {
  if (err) return handleError(err);
  // saved! return 200 or whatever you needs to do here
});

我解决了。 这很简单,我在为 body-parser 设置 app.use 之前已经导入了路由,所以它不知道解析 JSON 的热度,因此返回了一个未定义的主体。

app.use(bodyParser.json());

app.use("/meals", meals);
app.use("/orders", orders);

module.exports = app;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM