【问题标题】:MongoDB Post/ Create only Returning ID :: Possible JSON Formatting IssueMongoDB Post/Create only Returning ID :: 可能的 JSON 格式问题
【发布时间】:2021-09-13 20:53:21
【问题描述】:

我目前正在参加全栈 Web 开发人员训练营课程,并负责使用 CRUD 操作创建我的第一个 MERN Stack 应用程序。

创建新项目时,仅显示 id。我已经在 Postman 上对此进行了测试,它可以工作,但不能通过应用程序。

请看下面:

  • 邮递员:

  • 应用:

这很可能是关于 JSON 格式的问题,我试图通过添加标题、利用字符串化和解析信息来解决这个问题。我不太确定我哪里出了问题。

我的代码如下:

  • 服务器:carsModel.js:
const mongoose = require("mongoose");

const carSchema = mongoose.Schema({
  Model: {
    type: String,
  },
  Make: {
    type: String,
  },
  Owner: {
    type: String,
  },
  Registration: {
    type: String,
  },
  Address: {
    type: String,
  },
  previousOwners: {
    type: Array,
  },
});

module.exports = mongoose.model("Cars", carSchema);
  • 服务器:carsController.js:
exports.createController = (req, res) => {
  let car = new Car({
    Model: req.body.Model,
    Make: req.body.Make,
    Owner: req.body.Owner,
    Registration: req.body.Registration,
    Address: req.body.Address,
    previousOwners: req.body.previousOwners,
  });
  car
    .save()
    .then((cars) => res.json(cars))
    .catch((err) => res.status(400).json("Error creating the car." + err));
};
  • 服务器:carsRouter.js:
router.post("/create", cars.createController);
  • 服务器:server.js:
const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const logger = require("morgan");
const helmet = require("helmet");
const dbConfig = require("./config/db.config.js");
const carRoutes = require("./routes/carsRouter.js");

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(logger("dev"));
app.use(cors());
app.use(express.json());

app.use(helmet());

const uri = `mongodb+srv://${dbConfig.DB_USERNAME}:${dbConfig.DB_PASSWORD}@cluster1.4xta9.mongodb.net/test?retryWrites=true&w=majority`;
console.log(
  `mongodb+srv://${dbConfig.DB_USERNAME}:${dbConfig.DB_PASSWORD}@cluster1.4xta9.mongodb.net/test?retryWrites=true&w=majority`
);

mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
console.log(uri);

mongoose.connection.on("error", function () {
  console.log("Could not connect to the database. Exiting now...");
  process.exit();
});

mongoose.connection.once("open", function () {
  console.log("MongoDB database connection established successfully");
});

app.use("/cars", carRoutes);

const PORT = process.env.PORT || 8080;
app.listen(PORT);
console.log(
  "Navigate to http://localhost:8080/cars. Server is listening on port",
  PORT
);

app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  res.status(err.status || 500);
  next(err);
});
  • 客户端:carEdit.js:
const create = (e) => {
    e.preventDefault();

    axios
      .post("cars/create", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          Model,
          Make,
          Owner,
          Registration,
          Address,
          previousOwners,
        }),
      })
      .then((response) => {
        Swal.fire({
          imageUrl: "./images/success.gif",
          imageWidth: 150,
          imageHeight: 150,
          imageAlt: "Error",
          confirmButtonColor: "#007aff",
          width: 400,
          title: "SUCCESS!",
        });
        setCars(response.data);
      })
      .catch((error) => {
        console.log(error);
        Swal.fire({
          imageUrl: "./images/exclamation.gif",
          imageWidth: 150,
          imageHeight: 150,
          imageAlt: "Error",
          confirmButtonColor: "#ff0000",
          width: 400,
          title: "ERROR!",
          text: "User data missing",
        }).then(function () {
          window.location.reload();
        });
      });
  };
            <Button
              type="button"
              title="Add New Car"
              onClick={(e) => create(e)}
            >
              <FontAwesomeIcon icon={faPlus} />
              Add
            </Button>

请在此处查看 GitHub 存储库的链接:https://github.com/ChanBos/MERN-Cars-Database-Application

【问题讨论】:

  • 我认为您的 axios 请求有问题,请参阅 request method aliases for axios.post is axios.post(url, data, config)
  • @Daphaz - 非常感谢。这解决了这个问题,也有助于解决我的应用程序中的其他功能问题。我非常感谢您的帮助。祝你有美好的一天。

标签: node.js json reactjs mongodb express


【解决方案1】:

感谢@Daphaz 提供的帮助,此问题已得到解决。

代码已被修改以排除以下部分,因为它已经由 Axios 处理:

        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({

最终代码如下:

客户端:carEdit.js:

const create = (e) => {
    e.preventDefault();

    axios
      .post("cars/create", {
        Model,
        Make,
        Owner,
        Registration,
        Address,
        previousOwners,
      })
      .then((response) => {
        Swal.fire({
          imageUrl: "./images/success.gif",
          imageWidth: 150,
          imageHeight: 150,
          imageAlt: "Error",
          confirmButtonColor: "#007aff",
          width: 400,
          title: "SUCCESS!",
        });
        setCars(response.data);
      })
      .catch((error) => {
        console.log(error);
        Swal.fire({
          imageUrl: "./images/exclamation.gif",
          imageWidth: 150,
          imageHeight: 150,
          imageAlt: "Error",
          confirmButtonColor: "#ff0000",
          width: 400,
          title: "ERROR!",
          text: "User data missing",
        }).then(function () {
          window.location.reload();
        });
      });
  };

【讨论】:

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