[英]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
}
}
并且只是对过程安全性的提示:如果refreshToken
和user
属于一起,您可能应该检查某个地方。 否则,具有有效refreshToken
的用户可以冒充任何其他用户登录...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.