简体   繁体   中英

Cross domain AJAX request failing

I'm trying to make a cross domain ajax request i have set the PHP headers on the receiving end and set the jQuery AJAX request but for some reason it works then you refresh the page and it fires a cors origin error with a response code of 503 which from my research its caused by CORS.

I have followed some instructions from here How do I send a cross-domain POST request via JavaScript?

Headers for api.mydomain.co.uk

header('Access-Control-Allow-Origin: https://mydomain.co.uk');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

jQuery for mydomin.co.uk

 $.ajax({ type: 'POST', url: "//api.mydomain.co.uk/application/mp/basket", crossDomain: true, xhrFields:{withCredentials: true}, data: {Route: "ItemCount"}, success: function(data) { $('.count').text(data); } });

Browser Response在此处输入图片说明

It turns out that some Plesk installations are a bit buggy and the 503 error comes from the proxy_fcgi apache process.

To temporaraily fix this error you need to set your application in plesk to use FastCGI instead of FPM served by Apache/Nginx.

I once had this issue and I solved by this, I created an .htaccess file in the target website I was trying to access.

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(mydomain)$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin *
</IfModule>

Its an IF condition if the domain which is requesting has mydomain in it then it will allow you to access.

The CORS policy should also specify which headers you can send.

The 503 is a little bit strange. I think you need to set Content-Type in the list of allowed headers, and maybe others. According to MDN these:https://developer.mozilla.org/en-US/docs/Glossary/simple_header are the headers that you don't need to explicitly send

header('Access-Control-Allow-Headers: Content-Type, etc');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM