【问题标题】:Req is unidefined, Anyone know this?? please help me [closed]Req 未定义,有人知道吗??请帮助我[关闭]
【发布时间】:2023-01-19 02:05:35
【问题描述】:

我创建了类,即 UserService 并在其中添加了 登录方法,但我不知道为什么 req 和 body 都是未定义的

文件用户服务.js

const user = require("../../database/models/usermodal")
var bodyParser = require("body-parser");
var jsonParser = bodyParser.json();
const bcrypt = require("bcryptjs");

const jwt = require("jsonwebtoken");
const {
        registerValidation,
        loginValidation,
    } = require("../validators/validation");

const verify = require("../validators/verifytoken");
const { any } = require("@hapi/joi");

class UserService {
    //create = async (data) => await user.create(data);
    getById = async (email) => await user.findOne({where:{email}});

    onlogin = async (req, res) => {

        const { error } = loginValidation(req.body);

        // Validate:
        if (error)
            return res.status(400).send(error.details[0].message);

        // Check the email
        const emailExist = await user.findOne({where:{email:req.body.email}});

        if (!emailExist)
            return res.status(400).send("Email Not found or password is incorect");
        // Password checeking:
        const validPass = await bcrypt.compare(
            req.body.password,
            emailExist.password
        );
        if (!validPass)
            return res.status(400).send("Invalid Password");

        const token = jwt.sign(
            { id: emailExist.id, first_name: emailExist.first_name, last_name: emailExist.last_name, email: emailExist.email },
            env.Variable.JWT
        );

        //res.body(token)
        res.header("Auth-token", token).send(token);
    };

    onsignup = async (req, res) => {
      console.log(req)
      const { error } = registerValidation(req.body);

      // Validate:
      if (error)
          return res.status(400).send(error.details[0].message);

      // Check the user if the email is already exist:
      const emailExist = await user.findOne({where:{email:req.body.email}});
      console.log(emailExist);
      if (emailExist)
          return res.status(400).send("Email already exist");

      // Hashing the password:
      const salt = await bcrypt.genSalt(10);
      const hashPassword = await bcrypt.hash(req.body.password, salt);

      const users = user.create({
          first_name: req.body.first_name,
          last_name: req.body.last_name,
          is_delete: req.body.is_delete,
          google_auth_token: req.body.google_auth_token,
          refresh_token: req.body.refresh_token,
          email: req.body.email,
          password: hashPassword,
      });

      res.status(200).json({
          success: true,
          data: users,
      });
    };
}

module.exports = new UserService();

它只是在端口 9090 上侦听本地主机并将请求的主体记录到控制台中。当我通过Postman 发送任何请求时,它输出“未定义”。为什么是这样?这是我的代码问题还是我使用 Postman 的问题?

你可以查看我的 ERROR here

文件用户控制器.js

const userService = require("../../services/userService");
const express = require("express");

//const {
//  registerValidation,
//  loginValidation,
//} = require("../../validators/validation");
const verify = require("../../validators/verifytoken");
//const { any } = require("@hapi/joi");

const env = require("../../../config/config");
//const { use } = require("../../routes/userRoute");

class UserController {
    onSingups = async() => {
        await userService.onsignup()
    }
    onlogin = async() => {
        await userService.onlogin();
    }
    
    onGetAllUsers = async (req, res) => {
        const users = await userService.getAll();
        res.status(200).json({
            success: true,
            data: users,
        });
    };
}

module.exports = new UserController();

文件用户路由.js

const express = require("express");
const userControllar = require("../controllers/public/userController");
const bodyParser = require("body-parser")
const verify = require("../validators/verifytoken")
var jsonParser = bodyParser.json()

const router = express.Router();

router.route("/").get(userControllar.onGetAllUsers);
router.route("/singup").post(jsonParser, userControllar.onSingups);
router.route("/login").post(jsonParser, userControllar.onlogin);
router.get("/data", verify, (req, res) => {
    res.send(req.user)
})

module.exports = router;

【问题讨论】:

  • 请将您的代码缩减为能够重现您的问题的最小示例。

标签: javascript node.js express undefined req


【解决方案1】:

你应该添加要求资源在控制器中:

class UserController {
  onSingups = async(req, res) => {
    await userService.onsignup(req, res)
  }
  onlogin = async(req, res) => {
    await userService.onlogin(req, res);
  }

  onGetAllUsers = async (req, res) => {
    const users = await userService.getAll();
    res.status(200).json({
      success: true,
      data: users,
    });
  };
}

【讨论】:

  • 你是说我在 controller.js 中添加了登录功能??@sonu sindhu
  • 不只是用 req, res 参数调用那个服务登录函数
  • 太好了,请接受答案,以便其他人发现它有用
猜你喜欢
  • 2022-07-07
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多