我已经尝试了所有,但帖子请求仍然给我一个空的。我在浏览器和邮递员中检查了这些值是通过有效载荷发送的,但是当通过路由器帖子获取时,req.body 为空
主要
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);
});
型号
const mongoose = require("mongoose");
const dataSchema = mongoose.Schema({
name: {
type: String,
},
});
const dataModel = mongoose.model("data", dataSchema);
module.exports = dataModel;
路线
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));
});
控制台输出 { _id: 6022f0c0b3dd8f2sdc5302f9 } {}
请求体是空的。请帮我解决这个问题。谢谢
答案 0 :(得分:0)
代码是正确的。但是,发布请求标头不存在。传递标头后,它按预期工作。
MyXMacro((a) (b) (57) (32))
MyXMacro((c) (d) (49) (32))