簡體   English   中英

在 NodeJs 中處理 promise 拒絕

[英]Handle promise rejection in NodeJs

我正在使用創建后端NestJs庫。 在我的代碼中,我使用了一個guard來檢查我的令牌是否仍然有效:

import {Injectable, CanActivate, ExecutionContext, HttpException, HttpStatus} from '@nestjs/common';
import { Observable } from 'rxjs';
import * as jwt from 'jsonwebtoken';

@Injectable()
export class AuthGuard implements CanActivate {
    canActivate(
        context: ExecutionContext,
    ): any | Promise<boolean> | Observable<boolean> {
        const request = context.switchToHttp().getRequest();
        const token =  request.headers.authorization.split(' ')[1];
            try {
                const decoded = jwt.verify(token, '123');
                console.log(decoded)
                return true
            } catch(e) {
                console.log('tkn error', e)
                throw new HttpException('User unauthorized', HttpStatus.UNAUTHORIZED);
            }
    }
}

我也有這個檢查刷新令牌的service

import {HttpException, HttpStatus, Injectable} from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
import {InjectRepository} from "@nestjs/typeorm";
import {User} from "../entities/user.entity";
import {Repository} from "typeorm";

@Injectable()
export class RefreshService {
    constructor(
        @InjectRepository(User)
        private usersRepository: Repository<User>,
    ) {

    }

    async refresh(res, req) {
        const userId =  req.headers['userid'];
        const refreshToken = req.headers.authorization.split(' ')[1];
        const user = await this.usersRepository.findOne({
            where: {
                id: userId,
            },
        });

        if (!refreshToken) {
            throw new HttpException('User unauthorized', HttpStatus.UNAUTHORIZED);
        }
        jwt.verify(refreshToken, 'refresh', function (err, decoded) {
            if (err) {
                console.log(err)
                throw new HttpException('User unauthorized rt', HttpStatus.UNAUTHORIZED);
            } else {
                const token = jwt.sign({foo: 'bar'}, '123', {expiresIn: '55s'});

                res.send({
                    message: "You are logged in",
                    timestamp: new Date().toISOString(),
                    token: token,
                    user: user
                });
            }
        });

        console.log('refresh', refreshToken)
        res.send(refreshToken)
    }
}

即使我使用了try catch ,我也會在控制台中收到錯誤:

[0] (node:1444) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
[0] (node:1444) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我也得到:

[0] (node:15492) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

問題:我在上面的代碼中有哪些錯誤? 如何解決它們?

你拋出了一些在任何地方都沒有發現的異常

canActivate(context: ExecutionContext): any | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    const token =  request.headers.authorization.split(' ')[1];
    try {
        const decoded = jwt.verify(token, '123');
        console.log(decoded)
        return true
    } catch(e) {
        console.log('tkn error', e)
        //remove the exception here and just return false
        return false;
    }
}

此外,在您的第二個片段中,您為相同的res object 調用res.send(..)兩次,這會導致您看到的Error [ERR_HTTP_HEADERS_SENT] 此外,當找不到用戶時,您可能還需要一些錯誤處理......

async refresh(res, req) {
    const userId =  req.headers['userid'];
    const refreshToken = req.headers.authorization.split(' ')[1];
    const user = await this.usersRepository.findOne({
        where: {
            id: userId,
        },
    });

    if (user && refreshToken) {
        jwt.verify(refreshToken, 'refresh', function (err, decoded) {
            if (err) {
                console.log(err);
                //remove the exception and send an appropriate response
                res.sendStatus(401);
            } else {
                const token = jwt.sign({foo: 'bar'}, '123', {expiresIn: '55s'});
                res.send({
                    message: "You are logged in",
                    timestamp: new Date().toISOString(),
                    token: token,
                    user: user
                });
            }
        });
    } else {
      //if no user or no refreshToken is found 
      res.sendStatus(401); //send unauthorized status
    }
}

並且只是對過程安全性的提示:如果refreshTokenuser屬於一起,您可能應該檢查某個地方。 否則,具有有效refreshToken的用戶可以冒充任何其他用戶登錄...

暫無
暫無

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

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