【问题标题】:JSON POST requests empty response on Node/MongoJSON POST 在 Node/Mongo 上请求空响应
【发布时间】:2021-01-21 19:50:19
【问题描述】:

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

我正在尝试按照教程制作 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;

谢谢。

【问题讨论】:

  • 正如你所说,你得到了 201 响应,这可能是由上面代码中的这一行 .then(x => res.status(201).send(x)); 返回的,Meals.create(req.body) ,如果你能够连接,你可能必须先调试,如果Meals.create 正在运行
  • 我使用“isConnected()”和“on error”方法进行了检查,它说它已连接。有没有其他的调试方法?
  • 我发布了一个错误处理程序的示例
  • 谢谢。我解决了。路由和模型都很好,我在导入body-parser之前已经导入了路由,所以它不知道如何解析JSON,因此返回了undefined。

标签: node.js json post mongoose


【解决方案1】:

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

app.use(bodyParser.json());

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

module.exports = app;

【讨论】:

    【解决方案2】:

    要调试试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      相关资源
      最近更新 更多