【问题标题】:TypeError: Cannot read properties of undefined (reading 'strEmail') How can I solve this problem?TypeError: Cannot read properties of undefined (reading 'strEmail') 我该如何解决这个问题?
【发布时间】:2022-06-10 19:55:14
【问题描述】:

我正在使用 Express.js 编写此代码来进行简单的登录发布请求:

app.post("/login", (req, res) => {
  res.send(
    {
    isUserRegistered: userLogin(req.body.strEmail, req.body.strPassword),
    }
  )
})

function userLogin(strEmail, strPassword) {
  if (strEmail.includes("mike@gmail.com") , strPassword.includes("12345")) {
    return true;
  } else {
    return false;
  }
}

我的身体(原始):

{
    "strEmail":"mike@gmail.com",
    "strPassword":"12345"
}

预期的响应是isUserRegistered:True,这取决于我将在邮递员的正文中传递什么,有什么帮助吗?

【问题讨论】:

  • 你在 Express 中使用正文解析器吗?你可能不是,这就是为什么身体没有被解析并且以undefined 的形式出现的原因。如果你使用 Express 5,你可以在你的路由之前添加app.use(express.json()),否则安装body-parser并使用app.use(bodyParser.json())(确保首先需要body-parser)。
  • 此外,您必须在使用来自用户的所有参数之前对其进行有效性检查。您不能相信来自用户的信息。它可能是空的,可能包含非法字符,可能是垃圾。此外,当您收到这样的错误时,为什么不直接插入 console.log(req.body) 并准确查看您拥有的内容。在执行调试的第一步之前,您不应该来到这里。
  • 很高兴你把它修好了。顺便说一句,您可能想要使用res.json({ ... }) 而不是res.send({ ... })。我也不确定你为什么要使用 includes 而不是平等。

标签: javascript node.js express


【解决方案1】:

问题在于这里的范围。

创建一个名为utils 的文件夹并在其中创建一个userAuthentication.js 文件。 userAuthentication.js:

function userLogin(strEmail, strPassword) {
  if (strEmail === "mike@gmail.com" && strPassword === "12345") {
    return true;
  } else {
    return false;
  }
}

module.exports = userLogin;

在您的 app.js 或 index.js 文件中:

const express = require('express');
const userLogin = require('../utils/userAuthentication');
const app = express();
const port = 4000;

app.use(express.json());

app.post('/login', (req, res) =>{
  const { strEmail, strPassword } = req.body;
  const isAuthenticated = userLogin(strEmail, strPassword);
  if (isAuthenticated) {
    res.status(200).json({
      status: 'Ok',
      message: 'A user successfully logged in'
    });
  } else {
    res.status(500).json({
      status: 'Fail',
      message: 'Wrong credentials'
    }
});

【讨论】:

    猜你喜欢
    • 2021-11-10
    • 2021-11-03
    • 2021-11-08
    • 2022-06-23
    • 2023-02-09
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2022-07-09
    相关资源
    最近更新 更多