首页 > 解决方案 > TypeError:无法解构“req.body”的属性“email”,因为它未定义。(设置 MERN 身份验证)

问题描述

我对后端和 MERN 很陌生。对于任何滥用白话的行为,我深表歉意。我正在尝试使用 MERNInsomnia作为REST API CLIENT设置基本身份验证。正如我在脚本中编写的那样,使用 npm run dev 启动服务器运行良好。我还使用nodemonjwbbcryptjsmongoosedotenv作为依赖项。

发布注册请求效果很好:Insomnia Screenshot 1

但是发布这样的登录请求:Insomnia Screenshot 2在我的路由器中解构 req.body 时会导致错误,如下所示:TypeError: Cannot destructure property 'email' of 'req.body' as it is undefined. at C:\Users\mackm\Desktop\Folders 2\vscode_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;```

  

标签: node.jsmongodb

解决方案


您可以使用 body-parser 模块轻松使用 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,您将找到请求的内容。


推荐阅读