req.body is undefined even though it worked a couple of days ago, i even tried using the now depreciated body-parser and nothing, this is my code:
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"
}
}
I've been really struggling with this issue for the past few days, any help would be appreciated
CodePudding user response:
Your HTML form is configured for "multipart/form-data"
, but you have no middleware on your server to read and parse that content type so therefore req.body
remains undefined
since no middleware matched the content-type.
For such a simple form, you can just use application/x-www-form-urlencoded
as the content-type (which is the default content-type when none is specified) and your app.use(express.urlencoded())
will read and parse that content-type and will fill req.body
for you.
Just remove the enctype in your form and it will default to application/x-www-form-urlencoded
:
<body>
<form action="/upload-new" method="post">
<input type="text" name="name" />
<button type="submit">submit</button>
</form>
</body>
CodePudding user response:
did you try requesting the api endpoint "/upload-new" using postman or other http clients?