【问题标题】:How to add to all responses 'Access-Control-Allow-Origin' header?如何添加到所有响应“Access-Control-Allow-Origin”标头?
【发布时间】:2020-02-25 20:12:15
【问题描述】:

我是网络开发新手,我尝试学习游戏框架。对于后端部分,我使用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.

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

【问题讨论】:

  • 您可以使用HTTP_INTERCEPTOR 为所有请求添加标头。
  • @piedpiper 你能给我一些例子或者我可以在哪里读到这个吗?
  • @John HTTP_INTERCEPTOR 不是要走的路。 CORS -always- 需要在服务器上配置。因此,您必须在 play framework 中寻找解决方案

标签: angular scala playframework


【解决方案1】:

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

为此,您需要允许 Web 服务器接受 CORS(跨源请求)策略。 Play 开箱即用。详情请查看: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
  }
}

希望对您有所帮助!

【讨论】:

  • @John 我很乐意提供帮助!
猜你喜欢
  • 2011-06-27
  • 2014-03-30
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2017-01-18
  • 2023-01-13
  • 2016-07-03
相关资源
最近更新 更多