angular - 如何添加到所有响应“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.
这是因为我从另一个域发送请求。而且我不想在所有控制器中添加标头我想在一个地方将此标头添加到将从服务器发送的所有响应中。
我该怎么做?
解决方案
从我看到的你想从你的 Angular Web 应用程序页面调用另一个源:http://localhost:4200
Angular 页面源和http://localhost:9000
Play 框架应用程序的源。
为此,您需要允许 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
}
}
希望这有帮助!
推荐阅读
- c# - C# List.AddRange in Parallel.For 发生 ArgumentException
- firebase - Google Cloud Platform 网络控制台 - 云功能指标图表未显示
- c++ - OpenCV:加载缓慢
- c# - Richtextbox 拖放不同于表单拖放
- c# - 如何防止对象传递到另一种形式?
- c++ - 如何通过将签名作为模板参数来解析重载函数?
- windows - 如何在 Windows 中将 PostgreSQL ('psql.exe') 添加到 PATH?
- c# - 如何让WebClient在C#中逐行读取
- angular - 在 *ngFor 循环中引用子集合/文档
- java - sun.awt.X11FontManager: java.lang.reflect.InvocationTargetException (Arch Linux)