0

I have an AngularJS app which runs at http://localhost:9000. The front end app does a http request against http://localhost:8088. So, I had to setup the CORS on response headers.

I added on client side:

delete $http.defaults.headers.common["X-Requested-With"];
$http.defaults.headers.common["Accept"] = "application/json";
$http.defaults.headers.common["Content-Type"] = "application/json";

and on the server side (ExpressJS):

app.use(function(req, res, next) {  
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Origin", "*");  
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');  
    next();  
});

Everything works fine while I am calling //localhost:9000 -> //localhost:8088. But, when I do a redirect to a different url (//api.example.com/authorize) I got the following error in browser console: XMLHttpRequest cannot load //api.example.com/authorize?response_type=code. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

 app.use(function(req, res, next) {  
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
     res.header("Access-Control-Allow-Origin", "*");
     res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
     next();
 });

 app.get('/authorize', function (req, res) {  
    var response = 'https://api.example.com/authorize?response_type=code';  
    res.redirect(response);  
 });  

Do you have any clue what it is wrong?

Zygabel
  • 1
  • 2
  • Yeah, the problem is that https://api.example.com isn't responding with the Access-Control headers. – idbehold Mar 21 '16 at 17:53

1 Answers1

0

It seems like the issue has to do with redirection and CORS. Redirections with the status codes of 301, 302, 303, 307, or 308, will get you an error. This is being changed, but for now you need a workaround such as sending back the redirect URL in the response header or body, without using a redirect.

This is well explained in this other reply

Quoting from there:

Until browsers catch up, the only feasible options seem to be one or a combination of:

  1. Issue redirects only for simple requests.
  2. Issue a 305 redirect, with your own URL in the Location header as the "proxy". Be prepared for limited browser support, as 305 is deprecated.
  3. Do a fake "redirect":
    • return HTML with meta refresh and/or Javascript Location change.
    • return HTML that has a viewport-filling iframe with the redirect target as the iframe's source.
    • display a link that the user has to click in order to access the content.

In the end what i did was to put the link on the client side, I think it's the easiest and cleanest.

Community
  • 1
  • 1
Fab
  • 1,745
  • 2
  • 8
  • 11