【问题标题】:JWT Authorization failingJWT 授权失败
【发布时间】:2021-08-29 09:29:20
【问题描述】:

所以,我有这个代码。它曾经工作,但由于某种原因,它现在失败了。我很确定这部分代码失败了。前端的错误显示登录失败,请重试。其他所有工作文件,我可以从数据库中获取现有用户详细信息,但仍然失败。

  try{
    token = jwt.sign({userId: existingUser.id, email: existingUser.email},
       process.env.JWT_KEY,
       {expiresIn: '1h'});
    user.token = token;
  }catch(err){
    const error = new HttpError(
      'Logging in failed, please try again', 500
    );
    return next(error);
  }

谁能帮我解决这个问题。以下是该文件的完整代码。

const { uuid } = require('uuidv4');
const {validationResult} = require('express-validator');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const fileUpload = require('../middleware/file-upload');

const User = require('../models/user');
const HttpError = require('../models/http-error');

const getUserById = async (req, res, next) =>{
  const userId = req.params.uid;

let user;
  try{
    user = await User.findById(userId);
  }catch(err){
    const error = new HttpError('Something went wrong, could not find a post', 500);
    return next(error);
  }

  if(!user){
    return next(new HttpError('Could not find a user for the provided id.', 404));
  }

  res.json({ user: user.toObject({getters: true}) });
};

const signup = async (req, res, next) => {
  const errors = validationResult(req);
  if(!errors.isEmpty()){

    return next(new HttpError('Invalid inputs passed, please check your data.', 422))
  }

  const {name, email, password} = req.body;

  let existingUser;
  try{
      existingUser = await User.findOne({email : email});
  }catch(err){
    const error = new HttpError(
      'Signup failed, please try again.', 500
    );
    return next(error);
  }

  if(existingUser){
    const error = new HttpError(
      'User exists already, please login instead.', 422
    );
    return next(error);
  }


  let hashedPassword;
  try{
    hashedPassword = await bcrypt.hash(password, 12);
  }catch(err){
    const error = new HttpError('Could not create user, please try again', 500);
    return next(error);
  }


  const createdUser = new User({
    name,
    email,
    password: hashedPassword,
    posts: []
  });

  try{
    await createdUser.save();
  }catch(err){
    const error = new HttpError(
      'Signup failed, please try again', 500
    );
    return next(error);
  }

  let token;
  try{
    token = jwt.sign({userId: createdUser.id, email: createdUser.email},
       process.env.JWT_KEY,
       {expiresIn: '1h'});
  }catch(err){
    const error = new HttpError(
      'Signup failed, please try again', 500
    );
    return next(error);
  }


  res.status(201).json({userId: createdUser.id, email: createdUser.email, token: token});
};

const login = async (req, res, next) => {
  const {email, password} = req.body;

  let existingUser;
  try{
    console.log("Testing 1");
      existingUser = await User.findOne({email : email});
      console.log(existingUser);
  }catch(err){
    const error = new HttpError(
      'Logging in failed, please try again.', 500
    );

    return next(error);
  }

  if(!existingUser){
    const error = new HttpError(
      'Invalid credentials, could not log you in.',  403
    );
    return next(error);
  }

  let isValidPassword = false;
  try{
    isValidPassword = await bcrypt.compare(password, existingUser.password);
  }catch(err){
    const error = new HttpError('Could not log you in, please check your credentials and try again.', 500);
    return next(error);
  }

  if(!isValidPassword){
    const error = new HttpError(
      'Invalid credentials, could not log you in.',  401
    );
    return next(error);
  }

  let token;
  try{
    token = jwt.sign({userId: existingUser.id, email: existingUser.email},
       process.env.JWT_KEY,
       {expiresIn: '1h'});
    user.token = token;
  }catch(err){
    const error = new HttpError(
      'Logging in failed, please try again', 500
    );
    return next(error);
  }

  res.json({
    userId: existingUser.id,
    email: existingUser.email,
    token: token
  });
};

exports.getUserById = getUserById;
exports.signup = signup;
exports.login = login;

【问题讨论】:

  • 控制台从catch(err)记录err并检查错误是什么?
  • “await User.findOne({email : email})”的错误信息相同。尝试控制台记录错误并检查它是什么。

标签: node.js reactjs mongodb express react-fullstack


【解决方案1】:

此错误很可能是同步错误。

使用承诺链。

示例代码

new Promise((resolve, reject) => {
    // write code here.
    resolve(process);
})
.then((process) => {
    return process; 
})
.then((process) => {
    console.log(process);
})
.catch((err) => {
    console.log(err);
});

按照上面的代码处理您的逻辑。这是一种避免同步错误的方法。

【讨论】:

    猜你喜欢
    • 2020-02-16
    • 1970-01-01
    • 2021-07-23
    • 2021-12-08
    • 1970-01-01
    • 2020-04-03
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多