簡體   English   中英

將 CORS 標頭添加到 Angular 6 中的響應

[英]Add CORS header to response in Angular 6

我正在嘗試從 Angular 6 中的后端服務器獲取一些數據,以便我可以用自己的方式對其進行可視化。 我已經准備了一個有效的 GET 請求,它可以對我需要的所有數據進行正確的響應,但問題是當它以典型方式使用時,例如在“普通”瀏覽器中,我收到了 CORS 錯誤 -標題丟失。 那么即使有這個問題,我如何獲取數據呢? 通常,您必須在服務器端允許它,但這種情況有點不同。 我已經安裝了一個 Chrome 插件來為每個請求添加標頭。 使用該插件,CORS 問題不再存在。

所以我的問題是,如何(以及是否)將我的 Angular 代碼中的 CORS 標頭添加到響應中,這樣我就不必使用任何插件並且該應用程序可以在每個瀏覽器上運行?

另外,為了防止任何評論,我獲得的所有數據都可以合法訪問,它們是我自己的,我只是在 Angular 中學習新東西。 據我所知,我應該使用攔截器,但我很確定我做錯了。 這是我的代碼:

http服務方式:

  getFullResponse(domain: string, projectName: string, credentials: Credentials) {
    console.log('RequestService method getIssuesForProject() fired');

    return this.http.get('https://' + domain + '.myserver.local/api/' + projectName,
      {
        headers: new HttpHeaders({'Authorization': 'Basic ' + btoa(credentials.username + ':' + credentials.password)}),
        observe: 'response'
      }
    );
  }

我寫的攔截器類:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      map(event => {
        if (event instanceof HttpResponse) {
          event = event.clone({
            headers: event.headers.set('Access-Control-Allow-Origin', '*')
          });
        }
        return event;
      })
    );
  }

}

這是 component.ts 類:

import {Component, OnInit} from '@angular/core';
import {RequestService} from '../../shared/service/RequestService.service';
import {Credentials} from '../../shared/model/credentials';

@Component({
  selector: 'app-project',
  templateUrl: './project.component.html',
  styleUrls: ['./project.component.css']
})
export class ProjectComponent implements OnInit {

  projectKey = '';
  headers;
  credentials: Credentials;

  constructor(private reqService: RequestService) {
  }

  ngOnInit() {
  }

  onSubmit(domainName: string, projectKey: string, user: string, password: string) {
    this.projectKey = projectKey;
    this.credentials = {
      username: user,
      password: password
    };
    this.reqService.getFullResponse(domainName, projectKey, this.credentials)
      .subscribe(resp => {
        const keys = resp.headers.keys();
        this.headers = keys.map(key => `${key}: ${resp.headers.get(key)}`);
      });
  }

}

我已經嘗試使用 app.module.ts 在這個鏈接下的方式使用攔截器。 這完全破壞了我的應用程序,因為即使打開了 CORS 插件,我也會收到 CORS 錯誤。 我在互聯網上找到的其他代碼示例使用的代碼如下

return next.handle(reqClone) 
       .map(event => { 
         if (event instanceof HttpResponse) { 
           event = event.clone({ 
             headers: event.headers.set('x-test-res', 'res-test-header') 
           }); 
         } 
         return event; 
}); 

在攔截器中,但我猜它適用於舊版本的 Angular,我不能以這種方式使用map方法,所以我嘗試在pipe內使用它,就像在文檔中使用的一樣。 盡管如此,我仍然缺少一些東西。

它不是那樣工作的。 Cors 是在服務器端處理的東西。 服務器管理員設置這些標頭並允許某些域的位置。 您應該適當地查看JsonP,或者如果您像您所說的那樣控制數據,請查看允許您的服務器上的域。 這些是訪問控制允許標題

當您在向服務器發出的跨源 http 請求中包含諸如Authorization 之類的某些標頭時,瀏覽器通常會向服務器發出OPTIONS飛行前)請求,要求允許Access-Control-Allow-Methods和允許Access-Control-Allow-標頭,您的服務器端代碼應該響應這些,以便瀏覽器實際發出您想要的 http 請求

您不需要為請求設置 Headers。 為了避免 Angular 中的CORS 錯誤,您應該將代理傳遞配置用於開發目的。

package.json附近添加一個名為proxy.conf.json的文件。 從您的請求獲取 URL 添加/proxy

 this.http.get('/proxy/api/' + 
  projectName).subscribe(resData => {
        console.log(resData);
  });

proxy.conf.json中將代理規則設置為

{
  "/proxy/*": {
  "target": "http://backendDomain:8080",
  "secure": false,
  "logLevel": "debug",
  "changeOrigin": true,
  "pathRewrite": {
  "^/proxy": "/"
  }
 }
}

稍加修改即可更改 serve 命令:

ng serve --proxy-config proxy.conf.json --port 55055 --host 0.0.0.0

現在對后端的請求將來自相同的角度域,並且不會再有CORS錯誤

注意:此 Proxy 配置僅用於開發目的。 對於生產環境,您應該在 webservers 中進行配置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM