【发布时间】: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