【问题标题】:TypeError: Cannot destructure property 'email' of 'req.body' as it is undefined. (Setting up MERN authentication)TypeError:无法解构“req.body”的属性“email”,因为它未定义。 (设置 MERN 身份验证)
【发布时间】:2021-03-02 15:59:30
【问题描述】:

我对后端和 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.js mongodb


    【解决方案1】:

    您可以使用 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你会找到请求的内容。

    【讨论】:

      【解决方案2】:

      问题解决了:

      userRouter.js不正确(原文)

      router.post("/login", async (res, req) => {
      

      正确(固定)

      router.post("/login", async (req, res) => {
      

      箭头函数的参数原本与预期代码相反

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-07
        • 2021-03-08
        • 2021-05-11
        • 2021-04-04
        • 2021-08-30
        相关资源
        最近更新 更多