首页 > 解决方案 > 无法访问使用 Angular 的 Oauth 2.0 保护的 API

问题描述

我有一个 Angular 项目,它需要访问受 OAuth 2.0 保护的 Web API。

但是,我在访问此 API 时遇到了 CORS 错误。

请在下面找到我的代码:

App.module.ts:

imports
...
@NgModule({
 declarations: [
  AppComponent
 ],
 imports: [
   BrowserModule,
   AppRoutingModule,
   HttpClientModule,
   AuthModule.forRoot({
      domain: 'https://test/v2/',
      clientId: 'xxx',
      clientSecret: 'xxxxx'
   }),
  ],
  providers: [{ provide: HTTP_INTERCEPTORS, useClass: AuthHttpInterceptor, multi: true },
    AuthService,
    HttpClient
  ],
   bootstrap: [
     AppComponent]
  })
 export class AppModule { }

app.component.html

 <button class="btn btn-primary btn-block" (click)="getInfo()">
   GetInfo
</button>

app.component.ts

  let responseData = this.http.get('https://test/v2/xxx');
responseData.subscribe(
  response => {
  },
  error => {
    console.log(error)
  }
);

我收到以下错误:

从源“http://localhost:4200”访问“https://test/v2/xxx”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问控制” -Allow-Origin' 标头出现在请求的资源上。

请帮我。

亲切的问候。

标签: angularapioauth-2.0

解决方案


推荐阅读