0

I'm trying to connect to an external POST api for authentication. I'm trying:

$http({
    method  : 'POST',
    url     : 'myURL',
    data    : {"j_username": "myUserName,"j_password": "myPassword"},
    headers : {
        'Content-Type': 'application/x-www-form-urlencoded',
    } 
})

But I'm getting this error :

XMLHttpRequest cannot load http://...url. Response for preflight is invalid (redirect)

Allan Pereira
  • 2,572
  • 4
  • 21
  • 28
Kira Layto
  • 443
  • 1
  • 4
  • 7

1 Answers1

2

That looks like a CORS problem. If the javascript is served from a different domain than the domain of the API you are calling then you will run into CORS problems. In short, the browser will detect that the javascript was served from domain A and that the API is on domain B. What happens next depends on what you are trying to do, In this case you are doing a POST, which means the browser will send a preflight check to the API server to ask if it is okay with this javascript from domain A accessing it. The server has to respond to say yes in order for the browser to allow the request through (in reality it's quite a bit more complicated than "saying yes", but you get the idea).

In short, you need to configure the API server to allow this. If it's not your API then you'd need to ask whoever owns that API if they can configure CORS to allow your javascript to access it.

If you do need to work with this kind of setup, it's worth taking the time to read up on it and understand it properly. On the other hand, it may be you were just spiking something with a local js file, in which case you just need to know that it won't work like that.

See also https://stackoverflow.com/a/23824093/11534.

Community
  • 1
  • 1
flytzen
  • 7,348
  • 5
  • 38
  • 54
  • server doesn't respond saying *"Yes"* .... this is an oversimplification of how CORS works – charlietfl May 14 '16 at 22:32
  • @charlietfll - absolutely agreed. I just wanted to explain the basic problem :) – flytzen May 14 '16 at 22:33
  • Do i need to do some more configuration ? – Kira Layto May 14 '16 at 22:38
  • @Kira: Yes, you need to configure the server. I have updated my answer and also linked to another SO q/a which has some more details. Good luck! – flytzen May 14 '16 at 22:41
  • @charlietfl i dont have access to server side all what i have is this : URL: myURL method: POST Content-Type :"application/x-www-form-urlencoded" Parameters: j_username :"username" j_password :"password" – Kira Layto May 14 '16 at 22:42
  • 1
    @KiraLayto not all API's are ajax accessible due to CORS. Some also have `jsonp` output, but not all. Not enough known here. Alternative is use a proxy on server you do control to get the data – charlietfl May 14 '16 at 22:44