Implementing Cross-Origin Resource Sharing (CORS) in play-framework version 2.5.x: A Step-by-Step Guide

My current challenge involves retrieving JSON data by sending a request to a Restful URL from localhost within an AngularJS-1 application.

The error that I encounter is as follows:

http://localhost:9000/mlm/user/all Failed to load resource: 
the server responded with a status of 404 (Not Found)

index.html:1 XMLHttpRequest cannot load http://localhost:9000/mlm/user/all. 

Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

Origin 'http://localhost:63342' is therefore not allowed access. 

The response had HTTP status code 404.

In this scenario, I am utilizing play-framework 2.5.4 (java).

Update 1: I have included CORS settings in app.conf

    play.filters {
    cors {
    # Filter paths by a whitelist of path prefixes
    pathPrefixes = ["/"]

    # The allowed origins. If null, all origins are allowed.
    allowedOrigins = null

    # The allowed HTTP methods. If null, all methods are allowed
    allowedHttpMethods = ["GET", "POST"]

    allowedHttpHeaders = ["Accept"]
    preflightMaxAge = 3 days
  }
}

Answer №1

Finally, I found a solution that worked for me.

After reading the official documentation, I discovered that the Filter.java code mentioned there did not work as expected:

import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import play.http.DefaultHttpFilters;

import javax.inject.Inject;

public class Filters extends DefaultHttpFilters {
    @Inject public Filters(CORSFilter corsFilter) {
        super(corsFilter);
    }
}

Instead, I found success with this version of the Filter.java code:

import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import play.http.HttpFilters;
import javax.inject.Inject;

public class Filters implements HttpFilters {

    @Inject
    CORSFilter corsFilter;

    public EssentialFilter[] filters() {
        return new EssentialFilter[] { corsFilter.asJava() };
    }
}

I want to express my gratitude to this helpful answer on a related question in Stack Overflow.

However, the million-dollar question remains: why does the official Filter.java code provided in the 2.5.x documentation fail to work properly?

Answer №2

There appears to be a bug within the framework related to the cast to DefaultHttpFilters.java. For more information, you can visit this link.

Ensure that you refer to the guide available at .

To address this issue, avoid using the default implementation of DefaultHttpFilters and instead implement the code provided below:

package filters;
import play.http.*;

import java.util.Arrays;

import play.mvc.EssentialFilter;

/**
 * Helper class with a varargs constructor for filters.
 */
public class MyDefaultHttpFilters implements HttpFilters {

  private final EssentialFilter[] filters;

  public MyDefaultHttpFilters(play.api.mvc.EssentialFilter... filters) {
    this.filters = Arrays.stream(filters).map(f -> f.asJava()).toArray(EssentialFilter[]::new);
  }

  @Override
  public EssentialFilter[] filters() {
    return filters;
  }
}

Your Filter class should be structured as shown below:

import javax.inject.*;
import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import filters.MyDefaultHttpFilters;

public class Filters extends MyDefaultHttpFilters {
    @Inject public Filters(CORSFilter corsFilter) {
        super(corsFilter);
    }
}

Answer №3

It may be necessary to include a CORS allow header on your server:

response.setHeader("Access-Control-Allow-Origin", "*");//cross domain request/CORS

If you're unsure what framework you're using, look for access to the response object and add something like this.

In addition, many clients conduct an http OPTIONS request prior to the actual request in order to verify supported options and server accessibility. If you detect that the http method is OPTIONS, you can simply output the headers and close the socket/connection without processing the full request.

Answer №4

This information is well documented.

You can set up the filter configuration in the application.conf file. Here's an example:

play.filters.cors {
  pathPrefixes = ["/some/path", ...]
  allowedOrigins = ["http://www.example.com", ...]
  allowedHttpMethods = ["GET", "POST"]
  allowedHttpHeaders = ["Accept"]
  preflightMaxAge = 3 days
}

play.filters {
    cors {
    # Filter paths by a whitelist of path prefixes
    pathPrefixes = ["/"]

    # The allowed origins. If null, all origins are allowed.
    allowedOrigins = null

    # The allowed HTTP methods. If null, all methods are allowed
    allowedHttpMethods = ["GET", "POST", "OPTIONS"]

    preflightMaxAge = 3 days
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the art of line breaks

Imagine I have a random block of text displayed in a single line, like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Due to various reasons such as width settings or text-zoom, the text may display as two or more lines on the viewer&apos ...

Inconsistently, Android WebView fails to register touch inputs

I am facing an issue with my Android Web Application that is installed on a Tablet (LGV700 - 4.4.2) dedicated for this purpose and powered 24/7. This application acts as a wrapper to a web application and includes some additional features, all loaded from ...

React - The select component has received an invalid value of `undefined` that is out of range

I am working on a material-UI dialogue form that sends data to my API. One of the fields in the backend database is binary and only accepts two possible options. How can I handle this in the dialogue code provided below? Below is the error message: Mate ...

Express get requests are failing to handle query strings

Whenever I try to extract the year and month from the URL like this: http://localhost:3000/api/posts/2018/4, the code doesn't seem to work properly. Instead, it returns an error saying: Cannot GET /api/posts/2018/4 Here's the JavaScript code I&a ...

Best practices for managing several models within the Ionic framework using PouchDB?

Hey there! I've been diving into PouchDB lately and have a question about handling multiple models. I've noticed that most examples focus on a single model, like the ones found in this tutorial and various to-do app demos where they use db.allDo ...

Having trouble loading items in a <select> tag with Jquery?

Dealing with a seemingly simple issue, I am struggling to figure out how to load items into a select using jQuery. Working with the Materialize theme available at: The code snippet in question: <div class="input-field col s12"> <s ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...

Where can I locate htmlWebpackPlugin.options.title in a Vue CLI 3 project or how can I configure it?

After creating my webpage using vue cli 3, I decided to add a title. Upon examining the public/index.html file, I discovered the code snippet <title><%= htmlWebpackPlugin.options.title %></title>. Can you guide me on how to change and cu ...

How to Retrieve Correct JSON Data from Mongoose Query in Node.js

I am currently working on an express application that utilizes mongoDB as the database and handlebars as my server-side templating engine. Unlike many applications, I have chosen not to incorporate AngularJS or Ajax into my project. One of the challenges ...

The error encountered with react createRef was caused by a faulty implementation

Here is the revised question post completing the answer In this particular code snippet, I have encountered an issue where my file browser opens correctly upon submission, however, the updated state is not reflected when I click the final submit button. ...

AngularJS - Troubleshooting: Why Directive is Unable to Access Ancestor's Required Controller

To access a directive controller from an ancestor directive, I am using the require property in the "child" directive. Here is an example of how it is implemented: mmDirectives.directive('mmMapActions', function() { return { restrict : &ap ...

Tips for combining HTML and JavaScript on a WordPress site

As a WordPress developer who is still learning the ropes, I have come across a challenge with embedding html and JavaScript onto a page. Currently, I am in the process of redesigning a company website and one of the tasks involves integrating a calculator ...

Utilizing Scrollify for seamless section scrolling with overflow effects

I have been experimenting with the Scrollify script (https://github.com/lukehaas/Scrollify) and facing an issue where my sections are longer than the user's screen, requiring them to scroll down to view all content. However, Scrollify doesn't al ...

What steps can I take to ensure that the full tingle modal, which includes an image, is visible when the

Upon loading the page, I noticed that if the browser width is greater than 540px, the modal displaying an image gets cut off (see figure below). What steps should I take to ensure that the vertical scroll bar appears immediately? https://i.sstatic.net/cJv ...

I'm looking for a way to track the progress of an ajax call. Specifically, I want to know how I

I am currently working on an AJAX call that executes a lengthy PHP script producing 20 different results. I aim to display the progress of each step within the script, such as 1/20 complete, 2/20 complete, 3/20 complete. Last updated on 29-12-2015 at 03:1 ...

What causes certain webpack / Babel ES6 imports without a specified extension to resolve as "undefined"?

When I try to import certain ES6 files (such as .js, .jsx, .ts, .tsx) using the syntax import ComponentName from './folder/ComponentName'; (without extension), they end up resolving as undefined. This occurs even though there are no errors from W ...

Is there a way to transmit the ENTER key press to the page setup dialog within Internet Explorer 7?

My code is designed to change the page orientation. It functions correctly in IE6, but encounters issues in IE7. Specifically, it stops at %a and fails to input the enter or tab keys needed to press 'OK'. var shell; function SetPrintProperties() ...

Having difficulty installing the yarn package from GitHub

I'm attempting to install a GitHub package using yarn. I've tried this process many times before, but I have not been successful with this particular repository: https://github.com/coolwanglu/pdf2htmlEX I have already attempted the following w ...

What is the process for utilizing datePipe in an Angular component?

How can I implement DatePipe in my Angular component? This is the code snippet that I am currently using. for (let i = 0; i < this.days.length; i++) { this.storeStart(this.days[i], null, null, null); } I have stored weekdays (Monday to Frid ...

What could be causing the server to not successfully receive the ajax request?

I need to conduct integration tests on a website that routes all requests through a proxy: var express = require("express"), http = require("http"), port = (process.env.PORT || 8001), server = module.exports = express(), httpProxy = requir ...