gpt4 book ai didi

javascript - 类型错误 : Cannot read properties of undefined when sending an EJS form to Express

转载 作者:行者123 更新时间:2023-12-05 08:03:09 25 4
gpt4 key购买 nike

<分区>

我是 nodeJS 的新手,signupRoutes.js 文件中的 req.body.emailreq.body.password 可以似乎没有在我的项目的前端获取表单数据。

知道为什么吗?具体错误是“TypeError: Cannot read properties of undefined (reading 'email')”

signup.ejs:

<form action='/signup' method="post">
<label for="email">Email:</label>
<input type="text" id="email" name="email"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>

signupRoutes.js:

const express = require('express');
const router = express.Router();

const User = require('../models/userModel');

router.get('/', (req, res) => {
res.render('./signup');
res.end();
});

router.post('/', (req, res) => {
const user = new User({
email: req.body.email,
password: req.body.password
});
user.save();
res.redirect('/index');
});

module.exports = router;

用户模型.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
}, {timestamps: true})

const User = mongoose.model('User', userSchema);
module.exports = User;

服务器.js:

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const ejs = require('ejs');

const homepageRoutes = require('./routes/homepageRoutes');
const signupRoutes = require('./routes/signupRoutes');
const loginRoutes = require('./routes/loginRoutes');

const dotenv = require('dotenv');
dotenv.config();
const dbusername= process.env.DB_USERNAME;
const dbpassword= process.env.DB_PASSWORD;
dbURI = `mongodb+srv://${dbusername}:${dbpassword}@testingcluster.ix9mpsg.mongodb.net/?retryWrites=true&w=majority`;
mongoose.connect(dbURI).then((result) => app.listen(4000)).catch((err) =>
console.log(err));

app.set('view engine', 'ejs');
app.use(express.static('assets'));

app.use("/index", homepageRoutes);
app.use("/signup", signupRoutes);
app.use("/login", loginRoutes);

感谢您的宝贵时间。旁注:我知道您需要为密码增加更多安全性,我现在只是测试将数据发布到 mongoDB 中。

这是我根据用户建议尝试的一件事。就是把email: req.body.email, signupRoutes.js 改成email: res.json({requestBody: req.body.email}) 以及在“server.js”中的路由上方添加 app.use(express.json());

它只是返回一个包含空对象的空白页面,它也没有将数据发布到 MongoDB。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com