angular 如何Http 如何設定 CORS (Cross-Origin Resource Sharing)

如果要對所有送出的 Request 做調整

之前我在寫後台的,就可以使用AOP的方式實作, 而Angular也有類似的架構
如果我們用 @angular/common/http Angular只要實作HttpInterceptor interface就可以了

實作 HttpInterceptor

在cmd輸入
ng g service BasicAuthHtppInterceptor
已建立BasicAuthHtppInterceptorService ,修改內容如下
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BasicAuthHtppInterceptorService implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    req = req.clone({
      setHeaders: { /*有關CORS的參數就可以改在這裡了*/
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': 'true',
        'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS, PATCH',
        'Access-Control-Max-Age': '86400'
      }
    });
    return next.handle(req);

  }
}

在 root moudle 套用此Interceptor

打開 AppModule (app.module.ts)
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EmployeeComponent } from './employee/employee.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { BasicAuthHtppInterceptorService } from './service/basic-auth-htpp-interceptor.service';
....

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [
    {
        ...
        /*加入此設定*/
      provide: HTTP_INTERCEPTORS, useClass: BasicAuthHtppInterceptorService, multi: true 
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
!!!大功告成 這樣Request 出去的 Header就會加上 CORS 的Header了



留言

這個網誌中的熱門文章

Google Map 單車路徑計算坡度和角度小工具

Google URL Shortener API 快速教學