Javascript 在NodeJs中处理承诺拒绝
我正在使用创建后端Javascript 在NodeJs中处理承诺拒绝,javascript,node.js,nestjs,Javascript,Node.js,Nestjs,我正在使用创建后端NestJs库。在我的代码中,我使用了保护来检查我的令牌是否仍然处于活动状态: import {Injectable, CanActivate, ExecutionContext, HttpException, HttpStatus} from '@nestjs/common'; import { Observable } from 'rxjs'; import * as jwt from 'jsonwebtoken'; @Injectable() export class
NestJs
库。在我的代码中,我使用了保护
来检查我的令牌是否仍然处于活动状态:
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);
}
}
}
即使我使用了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;
}
}
对于流程的安全性有一个提示:如果
refreshttoken
和user
属于同一类,您可能应该在某处进行检查。否则,拥有有效的refreshttoken
的用户可以冒充任何其他用户登录…您抛出的HttpExeption
s将永远无法捕获(至少在您向我们展示的代码中不会)。在第一次截取中,在catch
块内抛出异常。这一例外情况将在哪里被发现?同样在第二个代码段中,两个异常(一个在verify
之前,另一个在verify
的回调中)都不会被捕捉到。此外,一旦在第二个代码段中到达verify
,并且该verify
的回调没有抛出,您将发送两次响应,一次使用res.send(refreshToken)
和一次使用res.send({message:“您已登录”,…
,请仅对真正可执行并显示您的error@derpirscher,您能告诉我如何更改代码吗?这将非常有用res.sendStatus(401)之间有什么区别
和抛出新的HttpException('User unauthorized',HttpStatus.unauthorized);
?为什么在我写入res.sendStatus(401);
时不会出现错误?第一个会将结果发送回请求客户端。第二个会抛出从未捕获到的异常(可能不会将结果发送回客户端)
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;
}
}
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
}
}