简体   繁体   English

发布请求后快递nodejs正文为空

[英]express nodejs body is empty after post request

I have tried all out there but still the post request is giving me an empty.我已经尝试了所有的方法,但发布请求仍然给我一个空的。 I checked in browser and also in postman the values are sent via the payload, but when getting via the router post, req.body is empty我在浏览器和 postman 中检查了值是通过有效负载发送的,但是当通过路由器帖子获取时,req.body 为空

main主要的

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
// var bodyParser = require("body-parser");   body parser also didnt work

const app = express();
// app.use(
//   bodyParser.urlencoded({
//     extended: true,
//   })
// );
// app.use(bodyParser.json());

app.use(cors());
app.use(express.urlencoded({ extended: true }));  // interchanged this below express.json didnt work
app.use(express.json());


const PORT = 3009;

// import routes
const router = require("./routes/route");
app.use("/api", router);


// connect mongo start
const uri =
  "mongodb+srv://adminuser:password@cluster0.gtkdj.mongodb.net/mydb?retryWrites=true&w=majority";

const options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

mongoose.connect(uri, options);

const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
  console.log("Mongo Connected");
});

app.listen(PORT, () => {
  console.log("Port is connected at ", PORT);
});

model model

const mongoose = require("mongoose");

const dataSchema = mongoose.Schema({
  name: {
    type: String,
  },
});

const dataModel = mongoose.model("data", dataSchema);

module.exports = dataModel;

routes路线

const express = require("express");
const router = express.Router();
const dataModel = require("../model/schema");

router.post("/new_items", (req, res) => {
  const data = new dataModel({
    name: req.body.name,
  });
  console.log(data, req.body);
  data
    .save()
    .then((item) => res.send(item))
    .catch((err) => res.status(400).send(err));
});

console output { _id: 6022f0c0b3dd8f2sdc5302f9 } {}控制台 output { _id: 6022f0c0b3dd8f2sdc5302f9 } {}

The req body is empty.请求正文为空。 Please help me on this.请帮助我。 Thanks谢谢

The codes were correct.代码是正确的。 But, the post request header was not present.但是,发布请求 header 不存在。 After passing the header, it worked as intended.通过 header 后,它按预期工作。

  await fetch("http://localhost:3009/api/new_items/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json", // this was missing
    },
    body: JSON.stringify(body),
  })

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

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