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 ...