[英]req.body returning null in Express
我遇到了一個問題,並嘗試了無數在線解決方案。問題是 req.body 返回 null 或空,如下所示:{} 我一直在使用的代碼是這樣的:
import express from "express";
import bodyParser from "body-parser";
const app = express();
const PORT = process.env.PORT || 8348;
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(bodyParser.json());
app.post("/", (req, res) => {
console.log(req.body);
res.send(req.body);
res.end();
});
app.listen(PORT, () => {
console.log("Running on port 3000");
});
package.json 是這樣的:
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"nodemon": "^2.0.15"
}
}
您不再需要 bodyParser,而是使用 express 內置方法:
const express = requrie('express');
const app = express();
app.use(express.json()); // to parse json bodies and not only form-urlencoded
app.use(express.urlencoded({ extended: true }));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.