req.body 是未定義的,即使它在幾天前作業,我什至嘗試使用現在貶值的 body-parser 并且什么都沒有,這是我的代碼:
JS:
var express = require("express");
var router = express();
require("dotenv").config();
var mongoose = require("mongoose");
router.use(express.json());
router.use(express.urlencoded({ extended: true }));
router.get("/upload-new", function (req, res) {
res.render("forum2");
});
router.post("/upload-new", function (req, res) {
console.log(req.body.name);
});
EJS:
<body>
<form action="/upload-new" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<button type="submit">submit</button>
</form>
</body>
JSON:
{
"name": "myapp",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "nodemon ./bin/www"
},
"dependencies": {
"bootstrap": "^5.2.0-beta1",
"connect": "^3.7.0",
"connect-mongo": "^4.6.0",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"dotenv": "^16.0.1",
"ejs": "^3.1.8",
"express": "^4.18.1",
"express-session": "^1.17.3",
"fs": "^0.0.1-security",
"http-errors": "~1.6.3",
"mongodb": "^4.6.0",
"mongoose": "^6.4.1",
"morgan": "^1.10.0",
"nodemon": "^2.0.18",
"package-json": "^8.1.0",
"path": "^0.12.7",
"url": "^0.11.0"
}
}
在過去的幾天里,我一直在努力解決這個問題,任何幫助將不勝感激
uj5u.com熱心網友回復:
您的 HTML 表單已配置為"multipart/form-data",但您的服務器上沒有中間件來讀取和決議該內容型別,因此req.body仍然存在undefined,因為沒有中間件與內容型別匹配。
對于這樣一個簡單的表單,您可以只使用application/x-www-form-urlencodedcontent-type(當沒有指定時,這是默認的 content-type),您app.use(express.urlencoded())將讀取并決議該 content-type 并req.body為您填寫。
只需洗掉表單中的 enctype,它將默認為application/x-www-form-urlencoded:
<body>
<form action="/upload-new" method="post">
<input type="text" name="name" />
<button type="submit">submit</button>
</form>
</body>
uj5u.com熱心網友回復:
您是否嘗試使用郵遞員或其他 http 客戶端請求 api 端點“/upload-new”?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497624.html
標籤:javascript 节点.js 表示 不明确的 正文解析器
