簡體   English   中英

Bcrypt 錯誤:非法參數:字符串,未定義

[英]Bcrypt error: Illegal arguments: string, undefined

我正在嘗試創建一個登錄端點並發送身份驗證令牌但是當我發送創建用戶的請求時它工作正常但是當我發送登錄身份驗證請求時它發送響應作為內部服務器錯誤並且在控制台中它向我發送此錯誤:-

Illegal arguments: string, undefined
[nodemon] restarting due to changes...
[nodemon] starting `node server.js index.js`
    at _async (D:\Web Development\REACT PROJECTS\inotebook\backend\node_modules\bcryptjs\dist\bcrypt.js:286:46)    at D:\Web Development\REACT PROJECTS\inotebook\backend\node_modules\bcryptjs\dist\bcrypt.js:307:17
    at new Promise (<anonymous>)
    at Object.bcrypt.compare (D:\Web Development\REACT PROJECTS\inotebook\backend\node_modules\bcryptjs\dist\bcrypt.js:306:20)
7:17    at new Promise (<anonymous>)
    at Object.bcrypt.compare (D:\Web Development\REACT PROJECTS\inotebook\backend\node_modules\bcryptjs\dist\bcrypt.js:306:20)
    at D:\Web Development\REACT PROJECTS\inotebook\backend\routes\auth.js:73:42    at processTicksAndRejections (node:internal/process/task_queues:96:5)

這是我完整的 auth.js 代碼:-

const express = require('express');
const User = require('../models/User');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');

const JWT_SECRET = 'usisagoodb$oy';

// Create a User using: POST "/api/auth/createuser". No login required
router.post('/createuser', [
  body('name', 'Enter a valid name').isLength({ min: 3 }),
  body('email', 'Enter a valid email').isEmail(),
  body('password', 'Password must be atleast 5 characters').isLength({ min: 5 }),
], async (req, res) => {
  // If there are errors, return Bad request and the errors
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  try {
    // Check whether the user with this email exists already
    let user = await User.findOne({ email: req.body.email });
    if (user) {
      return res.status(400).json({ error: "Sorry a user with this email already exists" })
    }
    const salt = await bcrypt.genSalt(10);
    const secPass = await bcrypt.hash(req.body.password, salt);

    // Create a new user
    user = await User.create({
      name: req.body.name,
      password: secPass,
      email: req.body.email,
    });
    const data = {
      user:{
        id: user.id
      }
    }
    const authtoken = jwt.sign(data, JWT_SECRET);
    

    // res.json(user)
    res.json({authtoken})
    
  } catch (error) {
    console.error(error.message);
    res.status(500).send("Internal Server Error");
  }
})


// Authenticate a User using: POST "/api/auth/login". No login required
router.post('/login', [ 
  body('email', 'Enter a valid email').isEmail(), 
  body('password', 'Password cannot be blank').exists(), 
], async (req, res) => {

  // If there are errors, return Bad request and the errors
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  const {email, password} = req.body;
  try {
    let user = await User.findOne({email});
    if(!user){
      return res.status(400).json({error: "Please try to login with correct credentials"});
    }

    const passwordCompare = await bcrypt.compare(password, user.password);
    if(!passwordCompare){
      return res.status(400).json({error: "Please try to login with correct credentials"});
    }

    const data = {
      user:{
        id: user.id
      }
    }
    const authtoken = jwt.sign(data, JWT_SECRET);
    res.json({authtoken})

  } catch (error) {
    console.error(error);
    res.status(500).send("Internal Server Error");
  }


})
module.exports = router

我還嘗試替換 const bcrypt = require('bcryptjs'); 使用 const bcrypt = require('bcrypt');

但這也給了我這個錯誤:-

Error: data and hash arguments required    at Object.compare (D:\Web Development\REACT PROJECTS\inotebook\backend\node_modules\bcrypt\bcrypt.js:208:17)
    at D:\Web Development\REACT PROJECTS\inotebook\backend\node_modules\bcrypt\promises.js:29:12  
    at new Promise (<anonymous>)
    at Object.module.exports.promise (D:\Web Development\REACT PROJECTS\inotebook\backend\node_modules\bcrypt\promises.js:20:12)
    at Object.compare (D:\Web Development\REACT PROJECTS\inotebook\backend\node_modules\bcrypt\bcrypt.js:204:25)
    at D:\Web Development\REACT PROJECTS\inotebook\backend\routes\auth.js:73:42
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

當我使用 bcrypt.compare 函數時,主要是這部分代碼給我錯誤

const {email, password} = req.body;
  try {
    let user = await User.findOne({email});
    if(!user){
      return res.status(400).json({error: "Please try to login with correct credentials"});
    }

    const passwordCompare = await bcrypt.compare(password, user.password);
    if(!passwordCompare){
      return res.status(400).json({error: "Please try to login with correct credentials"});
    }


唯一看起來格格不入的是

let user = await User.findOne({email});

它應該是這樣的:

let user = await User.findOne({where:{email}});

你也可以在文檔中看到

const userEmail=req.body.email;
const userPassword=req.body.password;
let user = await User.findOne({email:userEmail});

你應該使用 bcrypt 而不是 bcryptjs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM