Node.js (已解决)TypeError:无法分解属性';电子邮件';属于';要求正文';因为它是未定义的。(设置MERN身份验证)
我对后端和MERN非常陌生。我为误用方言道歉。 我正在尝试使用MERN和作为REST API客户端设置基本身份验证使用npm run dev启动服务器时运行良好,正如我在脚本中所写的那样。我还利用了nodemon、jwb、bcryptjs、mongoose和dotenv作为依赖项 发布注册请求非常有效: 但是像这样发布登录请求:在如下所示的路由器中解构req.body时会导致错误:Node.js (已解决)TypeError:无法分解属性';电子邮件';属于';要求正文';因为它是未定义的。(设置MERN身份验证),node.js,mongodb,Node.js,Mongodb,我对后端和MERN非常陌生。我为误用方言道歉。 我正在尝试使用MERN和作为REST API客户端设置基本身份验证使用npm run dev启动服务器时运行良好,正如我在脚本中所写的那样。我还利用了nodemon、jwb、bcryptjs、mongoose和dotenv作为依赖项 发布注册请求非常有效: 但是像这样发布登录请求:在如下所示的路由器中解构req.body时会导致错误:TypeError:无法解构'req.body'的属性'email',因为它未定义。在C:\Users\mackm\
TypeError:无法解构'req.body'的属性'email',因为它未定义。在C:\Users\mackm\Desktop\Folders 2\vscode\u work\React Projects\AUTHMERN\routers\userRouter.js:65:13
server.js文件:
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();
//set up server
const app = express();
PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port: ${PORT}`));
//reads header of requests, if so: parses the json text into object and puts into request.body
app.use(express.json());
// connect to mongodb server
mongoose.connect(
process.env.MDB_CONNECT,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err) => {
if (err) console.error(err);
console.log("Connected to MongoDB");
}
);
//set up routes
app.use("/auth", require("./routers/userRouter"));
路由器/userRouter.js:
const User = require("../models/userModel");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
//register
router.post("/register", async (req, res) => {
try {
const { email, password, passwordVerify } = req.body;
//validation
if (!email || !password || !passwordVerify)
return res
.status(400)
.json({ errorMessage: "Please enter all required fields" });
if (password.length < 6)
return res
.status(400)
.json({ errorMessage: "Please enter password of 6 or more charac" });
if (passwordVerify !== password)
return res.status(400).json({ errorMessage: "Passwords have to match" });
const existingUser = await User.findOne({ email: email });
// Check for existing users
if (existingUser) {
return res.status(400).json({
errorMessage: "An account with this email already exists.",
});
}
// hash the password
const salt = await bcrypt.genSalt();
const passwordHash = await bcrypt.hash(password, salt);
//save a new user account to the database
const newUser = new User({
email,
passwordHash,
});
const savedUser = await newUser.save();
//sign the token
const token = jwt.sign(
{
user: savedUser._id,
},
process.env.JWT_SECRET
);
//send the token in an HTTP only cookie
res.cookie("token", token, { httpOnly: true }).send();
} catch (err) {
console.error(err);
res.status(500).send;
}
});
// log in
router.post("/login", async (res, req) => {
try {
console.log("login initiated");
const { email, password } = req.body;
//validate
if (!email || !password)
return res
.status(400)
.json({ errorMessage: "Please enter all required fields" });
const existingUser = await User.findOne({ email: email });
//handle non existent account
if (!existingUser)
return res
.status(401)
.json({ errorMessage: "Incorrect email or password" });
const passwordCorrect = await bcrypt.compare(
password,
existingUser.passwordHash
);
//match password
if (!passwordCorrect)
return res
.status(401)
.json({ errorMessage: "Incorrect email or password" });
//sign token
const token = jwt.sign(
{
user: existingUser._id,
},
process.env.JWT_SECRET
);
//send the token in an HTTP only cookie
res.cookie("token", token, { httpOnly: true }).send();
} catch (err) {
console.error(err);
res.status(500).send();
}
});
module.exports = router;```
router.post("/login", async (res, req) => {
router.post("/login", async (req, res) => {
const User=require(“../models/userModel”);
const bcrypt=require(“bcryptjs”);
const jwt=require(“jsonwebtoken”);
//登记册
路由器.post(“/register”),异步(req,res)=>{
试一试{
const{email,passwordVerify}=req.body;
//验证
如果(!email | | |!password | |!passwordVerify)
返回res
.地位(400)
.json({errorMessage:“请输入所有必填字段”});
如果(密码长度<6)
返回res
.地位(400)
.json({errorMessage:“请输入6个或更多字符的密码”});
如果(密码验证!==密码)
返回res.status(400).json({errorMessage:“密码必须匹配”});
const existingUser=wait User.findOne({email:email});
//检查现有用户
如果(现有用户){
返回res.status(400).json({
errorMessage:“具有此电子邮件的帐户已存在。”,
});
}
//散列密码
const salt=wait bcrypt.genSalt();
const passwordHash=await bcrypt.hash(密码,salt);
//将新用户帐户保存到数据库
const newUser=新用户({
电子邮件,
密码哈希,
});
const savedUser=wait newUser.save();
//在代币上签名
const token=jwt.sign(
{
用户:savedUser.\u id,
},
process.env.JWT_机密
);
//在仅HTTP的cookie中发送令牌
res.cookie(“token”,token,{httpOnly:true}).send();
}捕捉(错误){
控制台错误(err);
资源状态(500)。发送;
}
});
//登录
路由器.post(“/login”),异步(res,req)=>{
试一试{
console.log(“登录启动”);
const{email,password}=req.body;
//证实
如果(!电子邮件| |!密码)
返回res
.地位(400)
.json({errorMessage:“请输入所有必填字段”});
const existingUser=wait User.findOne({email:email});
//处理不存在的帐户
如果(!existingUser)
返回res
.地位(401)
.json({errorMessage:“错误的电子邮件或密码”});
const passwordCorrect=wait bcrypt.compare(
密码,
existingUser.passwordHash
);
//匹配密码
如果(!passwordCorrect)
返回res
.地位(401)
.json({errorMessage:“错误的电子邮件或密码”});
//签名令牌
const token=jwt.sign(
{
用户:现有用户。\u id,
},
process.env.JWT_机密
);
//在仅HTTP的cookie中发送令牌
res.cookie(“token”,token,{httpOnly:true}).send();
}捕捉(错误){
控制台错误(err);
res.status(500.send();
}
});
module.exports=路由器```
您可以使用body解析器模块轻松地使用req.body及其属性
const bodyparser = require('body-parser');
/*assuming an express app is declared here*/
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: true}));
然后,如果使用req.body
,您将找到请求的内容。问题已解决:
在userRouter.js中
不正确(原件):
const User = require("../models/userModel");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
//register
router.post("/register", async (req, res) => {
try {
const { email, password, passwordVerify } = req.body;
//validation
if (!email || !password || !passwordVerify)
return res
.status(400)
.json({ errorMessage: "Please enter all required fields" });
if (password.length < 6)
return res
.status(400)
.json({ errorMessage: "Please enter password of 6 or more charac" });
if (passwordVerify !== password)
return res.status(400).json({ errorMessage: "Passwords have to match" });
const existingUser = await User.findOne({ email: email });
// Check for existing users
if (existingUser) {
return res.status(400).json({
errorMessage: "An account with this email already exists.",
});
}
// hash the password
const salt = await bcrypt.genSalt();
const passwordHash = await bcrypt.hash(password, salt);
//save a new user account to the database
const newUser = new User({
email,
passwordHash,
});
const savedUser = await newUser.save();
//sign the token
const token = jwt.sign(
{
user: savedUser._id,
},
process.env.JWT_SECRET
);
//send the token in an HTTP only cookie
res.cookie("token", token, { httpOnly: true }).send();
} catch (err) {
console.error(err);
res.status(500).send;
}
});
// log in
router.post("/login", async (res, req) => {
try {
console.log("login initiated");
const { email, password } = req.body;
//validate
if (!email || !password)
return res
.status(400)
.json({ errorMessage: "Please enter all required fields" });
const existingUser = await User.findOne({ email: email });
//handle non existent account
if (!existingUser)
return res
.status(401)
.json({ errorMessage: "Incorrect email or password" });
const passwordCorrect = await bcrypt.compare(
password,
existingUser.passwordHash
);
//match password
if (!passwordCorrect)
return res
.status(401)
.json({ errorMessage: "Incorrect email or password" });
//sign token
const token = jwt.sign(
{
user: existingUser._id,
},
process.env.JWT_SECRET
);
//send the token in an HTTP only cookie
res.cookie("token", token, { httpOnly: true }).send();
} catch (err) {
console.error(err);
res.status(500).send();
}
});
module.exports = router;```
router.post("/login", async (res, req) => {
router.post("/login", async (req, res) => {
正确(固定):
const User = require("../models/userModel");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
//register
router.post("/register", async (req, res) => {
try {
const { email, password, passwordVerify } = req.body;
//validation
if (!email || !password || !passwordVerify)
return res
.status(400)
.json({ errorMessage: "Please enter all required fields" });
if (password.length < 6)
return res
.status(400)
.json({ errorMessage: "Please enter password of 6 or more charac" });
if (passwordVerify !== password)
return res.status(400).json({ errorMessage: "Passwords have to match" });
const existingUser = await User.findOne({ email: email });
// Check for existing users
if (existingUser) {
return res.status(400).json({
errorMessage: "An account with this email already exists.",
});
}
// hash the password
const salt = await bcrypt.genSalt();
const passwordHash = await bcrypt.hash(password, salt);
//save a new user account to the database
const newUser = new User({
email,
passwordHash,
});
const savedUser = await newUser.save();
//sign the token
const token = jwt.sign(
{
user: savedUser._id,
},
process.env.JWT_SECRET
);
//send the token in an HTTP only cookie
res.cookie("token", token, { httpOnly: true }).send();
} catch (err) {
console.error(err);
res.status(500).send;
}
});
// log in
router.post("/login", async (res, req) => {
try {
console.log("login initiated");
const { email, password } = req.body;
//validate
if (!email || !password)
return res
.status(400)
.json({ errorMessage: "Please enter all required fields" });
const existingUser = await User.findOne({ email: email });
//handle non existent account
if (!existingUser)
return res
.status(401)
.json({ errorMessage: "Incorrect email or password" });
const passwordCorrect = await bcrypt.compare(
password,
existingUser.passwordHash
);
//match password
if (!passwordCorrect)
return res
.status(401)
.json({ errorMessage: "Incorrect email or password" });
//sign token
const token = jwt.sign(
{
user: existingUser._id,
},
process.env.JWT_SECRET
);
//send the token in an HTTP only cookie
res.cookie("token", token, { httpOnly: true }).send();
} catch (err) {
console.error(err);
res.status(500).send();
}
});
module.exports = router;```
router.post("/login", async (res, req) => {
router.post("/login", async (req, res) => {
箭头函数的参数最初与预期代码相反