1

I am using Play Framework and Angularjs for my application. My requirement is to redirect Play framework page based on some parameter selected on UI.

Here is my code,

On Page I opened bootstrap modal dialog and on submit action calling angular post method,

$scope.loginToExt = function() {

  var data = $scope.env;

  $http.post('/login', {env: data})
    .success(function(data){
      //$scope.env = data
    })
    .error(function(data){
      console.log(data)
    });
};

Once I click submit on my modal it will call '/login' and based on my route mapping will call action method as below,

def login = Action(parse.json) { implicit request =>
val env = (request.body \ "env").as[String]

env match {
  case _ => {
    Redirect("https://google.com")
      .withHeaders(ACCESS_CONTROL_ALLOW_ORIGIN -> "*")
  }
}

Route file as below,

POST     /login             controllers.Application.login

I don't know what the issue is but I was getting error as below and unable to redirect my page.

XMLHttpRequest cannot load https://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

Nishan
  • 375
  • 3
  • 16

2 Answers2

1

I believe the issue you are having is because you are trying to redirect inside an ajax ($http.post) call, see this post:

Your server side code cannot redirect the browser from an ajax response.

Using $http.post and res.redirect without resolving the promise

See also: Handle an express redirect from Angular POST

Instead of trying to redirect from Play, consider returning a response with the url of the redirect, then in your success call back, redirect from there:

$window.location.href = "https://google.com";

(remember to inject $window)

Community
  • 1
  • 1
BatteryAcid
  • 8,381
  • 5
  • 28
  • 40
  • Thanks for your help...but is there any way I can redirect it from Play Controller ? – Nishan Sep 28 '15 at 06:27
  • I don't think so. See http://stackoverflow.com/a/15996968/1956540, in the comments it is pointed out that because of the nature of XHR requests, redirects in this fashion are not going to work. – BatteryAcid Sep 28 '15 at 13:10
  • Thanks again for you time. It seems difficult to achieve this using javascript so I have replace javascript logic with play html form and controller based native logic. No JavaScript used now and now it is working as expected. – Nishan Sep 28 '15 at 15:40
0

By looking https://gist.github.com/mitchwongho/78cf2ae0276847c9d332 , You have to add "access-control-allow-origin" in HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS in Global.scala file.

Arpit Suthar
  • 754
  • 1
  • 5
  • 19