I am working on a project (frontend) that will communicate with another (API) in another domain.
I am currently working on a local computer with this configuration:
- Frontend :
http://127.0.0.1:9000 - API :
http://127.0.0.1:9100
In my API program, I defined an OPTIONS request that returns these headers along with an HTTP 200 status code:
Access-Control-Allow-Headers:accept, origin, x-requested-with, content-type Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS Access-Control-Allow-Origin:* Access-Control-Max-Age:15 Content-Length:0
Using jQuery, I am making an Ajax request to this URL. For example, here is the request header for the OPTIONS request:
Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4 Access-Control-Request-Headers:accept, origin, x-requested-with, content-type Access-Control-Request-Method:POST Connection:keep-alive Host:127.0.0.1:9100 Origin:http://127.0.0.1:9000 Referer:http://127.0.0.1:9000/login User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31
This works successfully (status code: 200 OK), and then POST is done on http://127.0.0.1:9100/auth/login , as expected, but I got this in the "My Network" panel:
Status: Canceled | Type: Pending
If I look in the console, I got this error:
XMLHttpRequest cannot load http://127.0.0.1:9100/auth/login . The origin of http://127.0.0.1:9000 not allowed by Access-Control-Allow-Origin.
But, as we see, Access-Control-Allow-Origin is defined as "*". I also tried changing it to "127.0.0.1:9000" and " http://127.0.0.1:9000 ", the same error appears on the console.
Now, some details about my jQuery ajax team. The ajax itself is pretty simple:
jQuery.ajax({ 'url': '/auth/login', 'type': 'POST', 'data': {'login': 'abc', 'password': 'def'}, 'timeout': 15000 }).done(function (data, status, xhr) { console.log ('ok'); }).fail(function (xhr, status, description) { console.error('oups'); });
But the base API URL is added after using the jQuery.ajaxPrefilter method:
jQuery.ajaxPrefilter (function (options) { var url = document.createElement('a'); url.href = options.url; options.url = 'http://127.0.0.1:9000' + url.pathname; });
This is to avoid changing multiple files when changing the URL. I donβt know if this is the cause of the problem, but so far I cannot make a POST request, even if everything regarding the CORS configuration seems to be in order.
What have I done wrong?