John
John

Reputation: 1611

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

I'm new in web development and I try to learn play framework. For backend part I used play 2.8.x framework and for frontend angular 8. And I am facing some problem when I am trying to get a response from the server. At frontend part, I have only one button that sends a request to the server (play 2 framework). That is the following frontend code:

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));
  }
}

and on the server side I handle this request like the following:

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");
    }
}

and when the server sends the response to a browser I have the following error:

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.

It is because I send a request from another domain. And I don't want to add header in all controllers I want to add this header in one place to all responses which will be sent from the server.
How can I do it?

Upvotes: 1

Views: 1182

Answers (1)

Ivan Kurchenko
Ivan Kurchenko

Reputation: 4063

From what I see you want to invoke another origin from your Angular web application page: http://localhost:4200 Angular page origin and http://localhost:9000 origin for Play framework app.

In order to do this you need to allow web server accept CORS (cross origin request) policy. Play provide this out of the box. Please, see for more details: https://www.playframework.com/documentation/2.8.x/CorsFilter

Essentially you need to add play.filters.enabled += "play.filters.cors.CORSFilter" in your application.conf and it should work.

Another option: configure Angular development server to proxy request to Play for you, so you don't need enable CORS on Play framework side. Here is nice article with instruction: https://medium.com/better-programming/setup-a-proxy-for-api-calls-for-your-angular-cli-app-6566c02a8c4d

In this case you need to create proxy.conf.json file with next content

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

Hope this help!

Upvotes: 1

Related Questions