[英]Req.body is empty for POST request in Express
我尝试使用 Postman 生成我的网络的一些后期交易,但是当我检查我的代码的 post 方法时,它会打印空的 {} 并将空的 {} 添加到我的列表中。 我尝试使用中间件,但问题仍然存在。
这是我的代码。
// my code at restaurant.js const express = require("express"); const router = express.Router(); const restaurants = require("../data") router.get("/",(req,res) =>{ res.json(restaurants); } ) router.get("/:id",(req,res) =>{ const restaurantid = Number.parseInt(req.params.id,10); const restaurant = restaurants.find((restaurant) => restaurant.id === restaurantid); res.json(restaurant); }) router.post("/",(req,res)=>{ console.log(req.body); new_restaurant = req.body; restaurants.push(new_restaurant); res.json(new_restaurant); } ) module.exports = router; //my code at index.js const express = require("express"); const app = express(); const router = express.Router(); const restaurantsRouter = require("./routes/restaurants.js"); // Middleware app.use(express.json()); app.use(express.urlencoded({extended:false})); // Routes app.use("/apis/restaurants",restaurantsRouter); app.get("/",(req,res)=>{ res.send("<h1>Hello Express</h1>"); }); app.listen(3000,()=> { console.log("Listening to port 3000"); }) module.exports = router;
传入的 POST 请求中req.body
为空的一般原因如下:
application/json
。req.body
。因此,您需要通过 POST 请求并消除所有这些可能性,直到找到问题为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.