如何添加到所有回复 'Access-Control-Allow-Origin' header?

How to add to all responses 'Access-Control-Allow-Origin' header?

我是网络开发的新手,我尝试学习游戏框架。对于后端部分,我使用 play 2.8.x framework,对于前端,我使用 angular 8。当我试图从服务器获得响应时,我遇到了一些问题。在前端部分,我只有一个向服务器发送请求的按钮(播放 2 框架)。即以下前端代码:

import { Component } from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'ui';

  constructor(private http: HttpClient) {
  }

  helloServer():void {
    console.log("hello from client");
    let url = 'http://localhost:9000/api/hello';
    this.http.get<String>(url, {responseType: 'text' as 'json'}).subscribe((data: String) => console.log("Response from server: " + data));
  }
}

在服务器端,我按如下方式处理此请求:

package controllers;

import play.mvc.Controller;
import play.mvc.Result;

public class HomeController extends Controller {

    public Result index() {
        return ok("Hello from server.", "UTF-8");
    }
}

当服务器向浏览器发送响应时出现以下错误:

Access to XMLHttpRequest at 'http://localhost:9000/api/hello' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是因为我从另一个域发送请求。而且我不想在所有控制器中添加 header 我想在一个地方将此 header 添加到将从服务器发送的所有响应中。
我该怎么做?

据我所知,您想从 Angular 网络应用程序页面调用另一个来源:http://localhost:4200 Angular 页面来源和 http://localhost:9000 Play 框架应用程序来源。

为此,您需要允许 Web 服务器接受 CORS(跨源请求)策略。开箱即用。请查看更多详情:https://www.playframework.com/documentation/2.8.x/CorsFilter

基本上,您需要在 application.conf 中添加 play.filters.enabled += "play.filters.cors.CORSFilter",它应该可以工作。

另一种选择:配置Angular 开发服务器来为您代理对 Play 的请求,这样您就不需要在 Play 框架端启用 CORS。这是一篇带有说明的好文章:https://medium.com/better-programming/setup-a-proxy-for-api-calls-for-your-angular-cli-app-6566c02a8c4d

在这种情况下,您需要创建 proxy.conf.json 包含下一个内容的文件

{
  "/api": {
    "target": "http://localhost:9000",
    "secure": false
  }
}

希望对您有所帮助!