问题
I'm getting a req.body back when I submit my HTML form, but it's always an empty object. I'm testing in postman and also submitting the form from the localhost in the browser.
When I log it in the node console, it says [Object: null prototype]
I've read and tried all the (many) proposed solutions to similar things, but none seem to apply.
Thank you very much!
// homepage.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<link rel="stylesheet" href="homepage.css" />
</head>
<body>
<h1 class="greeting">Sign Up // Sign In</h1>
<div>
<form
action="http://localhost:3000/auth/signup"
method="POST"
class="inbox"
id="sign-up-form-id"
enctype="text/html"
>
<label for="sign-up-name-id">Sign Up: Name</label>
<br />
<input
class="name"
id="sign-up-name-id"
name="signUpNameName"
type="text"
placeholder="your name here"
required
/>
<br />
<label for="sign-up-password-id">Password</label>
<br />
<input
class="password"
id="sign-up-password-id"
name="signUpPasswordName"
type="password"
placeholder="create a password"
required
/>
<br />
<input class="btn" id="sign-up-btn" name="sign-up-btn" type="submit" />
</form>
</div>
<script src="homepage.js"></script>
</body>
</html>
// app.js
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const sassMiddleware = require("node-sass-middleware");
const authRouter = require("./routes/auth");
const indexRouter = require("./routes/index");
// import other routers here like:
// const postsRouter = require('./routes/posts');
const app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(
sassMiddleware({
src: path.join(__dirname, "public"),
dest: path.join(__dirname, "public"),
indentedSyntax: false, // true = .sass and false = .scss
sourceMap: true
})
);
app.use(express.static(path.join(__dirname, "public")));
app.use("/", indexRouter);
app.use("/auth", authRouter);
// add more routers here:
// app.use('/posts', postsRouter);
// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
});
// error handler
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
module.exports = app;
routes/auth.js
const express = require("express");
const { createUser } = require("../controllers/auth-controller");
const router = express.Router();
router.post("/signup", createUser);
module.exports = router;
controllers/auth-controller.js
const User = require("../models/User");
// const seeIt = (req, res) => {
// // const form = JSON.parse(JSON.stringify(req.body));
// console.log(req.body);
// };
const createUser = (req, res) => {
if (req.body) {
console.log("here: ", req.body);
}
User.create(req.body, err => {
if (err) res.status(500).json({ flash: err.message });
else res.status(200).json({ flash: "User created!" });
});
};
module.exports = { createUser };
回答1:
💡 The only one reason why you get something like this:
[Object: null prototype]
it's because { extended: false };
👨🏫 Now, you try to change your extended
to true
. For an example, you can look at this code below:
app.use(express.urlencoded({ extended: true}));
I've been try that code above and it's working fine
I hope it can help you 🙏.
回答2:
bodyParser is no longer using by node js
you should use app.use(express.json());
ONLY, it will takecare all the bodyParser work for you, and below that, write this piece of code ONLY ONCE
app.use(express.urlencoded({ extended: false }));
i noticed that you write above line twice, please write that only once
i hope this will work for you
来源:https://stackoverflow.com/questions/59994793/req-body-is-an-empty-object-from-simple-html-form-using-express