【发布时间】:2019-10-13 08:04:40
【问题描述】:
我有一个 Angular 7 应用程序和一个带有 JTW 的 Java Spring API。应用程序必须在 API 中的每个请求时发送令牌,但这不会发生,因此所有请求都会返回 401 错误。
应用模块
...
@NgModule
({
declarations: [
AppComponent,
PatientComponent,
HeaderComponent,
FooterComponent,
AlertComponent,
NotFoundComponent,
UserRegisterComponent,
LoginComponent,
AuthGuardComponent
],
imports: [
BrowserModule,
FormsModule,
NgSelectModule,
ReactiveFormsModule,
HttpClientModule,
AppRoutingModule,
NgbModule,
],
providers: [
{
provide : HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi : true,
},
],
bootstrap: [AppComponent]
})
export class AppModule {
}
AuthInterceptor
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { GeneralService } from '../_service/general.service';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private generalService: GeneralService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJTeXN0ZW0gVXNlciJ9XSwiaXNzIjoiaHR0cHM6Ly9hcGkubmVvZ3JpZC5jb20vIiwiaWF0IjoxNTU4OTgwOTAxLCJleHAiOjE1NTg5OTg5MDF9.vZByXryTI-1wGLYY1bU8DurOF15qlxA7QkdMW5UeM8c')
}
});
console.log(req);
return next.handle(req);
}
}
请求
listAll() {
return this.http.get('http://localhost:8080/api/listAll');
}
async get() {
let error = null;
let response = await this.listAll()
.toPromise()
.catch(error => error = error);
console.log(response);
}
console.log(req) 的结果;
看起来不错,授权和令牌都在那里
请求
不要在这里传递令牌:c
错误
OPTIONS 401 访问 XMLHttpRequest at'http://localhost:4200' 已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:它没有 HTTP 正常状态。
我对 insonmia 做了同样的请求(通过了授权和令牌),一切都很好,问题出在角度请求上。
【问题讨论】:
-
你能解释一下吗?
-
可能服务器设置不正确,因此拒绝了选项请求,但我们无法从您发布的内容中判断。参见例如stackoverflow.com/a/40723041/3001761
-
请求中没有发送token的angular是不是有问题?
-
我对 insonmia 做了同样的请求(通过了授权和令牌),一切都很好,问题出在角度请求上。
-
您阅读了链接吗?预检选项请求不应包含凭据。除非您完成了整个 CORS 周期并从失眠症中提出了选项请求,否则您对问题所在的位置是错误的。
标签: javascript angular request http-headers jwt