首页 > 解决方案 > 如何添加到所有响应“Access-Control-Allow-Origin”标头?

问题描述

我是网络开发的新手,我尝试学习游戏框架。对于我使用的后端部分 play 2.8.x framework和前端angular 8。当我试图从服务器获得响应时,我遇到了一些问题。在前端部分,我只有一个向服务器发送请求的按钮(play 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.

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

标签: angularscalaplayframework

解决方案


从我看到的你想从你的 Angular Web 应用程序页面调用另一个源:http://localhost:4200Angular 页面源和http://localhost:9000Play 框架应用程序的源。

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

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

另一种选择:配置 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
  }
}

希望这有帮助!


推荐阅读