您在预期流的位置提供了"未定义"。在令牌拦截器中



我正试图制作一个拦截器来刷新令牌,但它给我带来了这个错误,我不知道为什么

ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

token-interceptor.service.ts

import { Injectable } from '@angular/core';
import { AuthService } from './auth.service';
import { HttpClient, HttpErrorResponse, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { catchError, map} from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor {
constructor(
private auth: AuthService,
private http: HttpClient
) { }

intercept(req: HttpRequest<any>, next: HttpHandler) {
return next.handle(req).pipe(
catchError((err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.url.includes('signin') || err.url.includes('refreshToken')) {
return next.handle(req)
}
//if error is not about authorization 
if (err.status !== 401) {
return next.handle(req)
}

this.renewToken(req).subscribe(request => {
return next.handle(request)
})

} else {
return throwError(err)
}
})
)
}
renewToken(req: HttpRequest<any>) {
return this.http.get(`${environment.API_URL}/refreshToken`, { withCredentials: true }).pipe(
map((res: any) => {
//update access token
this.auth.setToken(res.token)
return req.clone({
setHeaders: {
authorization: `Bearer ${res.token}`
}
})
})
)
}
}

忽略这个:看起来你的帖子大多是代码;请添加更多详细信息。看起来你的帖子大部分都是代码;请添加更多详细信息

这段代码是错误的:

this.renewToken(req).subscribe(request => {
return next.handle(request)
})

它应该是:

return this.renewToken(req).pipe(switchMap(request => next.handle(request)));

您的变体中没有返回任何内容,这就是为什么它不起作用。

另外,代币交互接收器的整个逻辑在我看来很奇怪。我认为你应该重新思考你希望它如何工作。现在,正如我所看到的,你在没有令牌的情况下发送请求,并且在几乎所有情况下,你都是在未经修改的情况下再次发送请求,而我在上面修复的那个将使用令牌再次发送请求。每次添加令牌,如果令牌过期,只发送第二次,这不是正确的吗?

最新更新