【问题标题】:post request is not working properly, Some data are going but some are not发布请求无法正常工作,有些数据正在传输,但有些数据没有
【发布时间】:2021-03-31 13:47:21
【问题描述】:

请求:

{
    "title": "Wake up and smell the coffee",
    "message": "In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Wikipedia",
    "creator": "Shravan",
    "tags": [
        "tag1",
        "tag2"
    ],
    "selectedFile": "www.selectedfile.jpg"
}

回应:

{
    "tags": [],
    "likeCount": 0,
    "createdAt": "2020-12-21T19:12:05.908Z",
    "_id": "5fe0f38c8e9dcb0eb07a9a56",
    "__v": 0
}

模型/架构:

import mongoose from "mongoose";

const postSchema = mongoose.Schema({
  title: String,
  message: String,
  creator: String,
  tags: [String],
  selectedFile: String,
  likeCount: {
    type: Number,
    default: 0,
  },
  createdAt: {
    type: Date,
    default: new Date(),
  },
});

var PostMessage = mongoose.model("PostMessage", postSchema);

export default PostMessage;

Server.js:

import express from "express";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import cors from "cors";

import PostMessage from "./models/postMessage.js";
// routes
// import postRoutes from "./routes/posts.js";

const app = express();

app.post("/post", (req, res) => {
  const data = req.query;
  PostMessage.create(data, (err, data) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(200).send(data);
    }
  });
});

// limit: "30mb",
app.use(bodyParser.json({ extended: true }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

// app.use(express.json());

const CONNECTION_URL =
  "mongodb+srv://admin:admin@cluster0.9ey4m.mongodb.net/dbTest?retryWrites=true&w=majority";
const PORT = process.env.PORT || 5000;

mongoose
  .connect(CONNECTION_URL, {
    useCreateIndex: true,
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => app.listen(PORT, console.log(`Server running on port ${PORT}`)))
  .catch((error) => console.log(error.message));

// mongoose.set("useFindAndModify", false);

谁能帮帮我?

因为我没有得到任何正确答案,所以过去 5 天我一直在尝试寻找答案。

【问题讨论】:

  • 错误是什么?你能分享一下预期结果和实际结果吗?

标签: node.js mongodb api express mongoose


【解决方案1】:
  1. 中间件应位于路由之上,以便预处理请求对象。
  2. 如果是发布请求,req.query 应该是 req.body

req.body 是中间件存储从 Request 对象中提取的数据的位置,per docs

(...) 解析后的数据填充在中间件之后的请求对象上(即 req.body),如果没有要解析的主体,则 Content-Type 不匹配,则为空对象({}),或发生错误。

代码应该是:

//bodyparser package not needed anymore.

// 1. middlewares
app.use(express.json({ extended: true }));
app.use(express.urlencoded({ extended: true }));
app.use(cors()); //you can remove this an set header manually

// 2. routes
app.post("/post", (req, res) => {
  const data = req.body;
  PostMessage.create(data, (err, data) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(200).send(data);
    }
  });
});

【讨论】:

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