Pregunta

I have a php file that is sitting on a web server that has the following code to allow it to be accessed from other domains:

header('content-type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); 

When I make a request from my test server(s) I get the response on Chrome Dev Tools

> XMLHttpRequest cannot load http://beta.dean.technology/proxy.php. No
> 'Access-Control-Allow-Origin' header is present on the requested
> resource. Origin 'http://localhost' is therefore not allowed access.

An example request I have made is JSFiddle

$.ajax({url: 'http://beta.dean.technology/proxy.php',type:"POST",data: '{}',contentType:"application/json",dataType:"json"})

I have also used online HTTP header inspectors and they are replying with "Access-Control-Allow-Origin: *". I have also placed this file on different servers and still the same results. The file can be accessed by going to the url normally.

Has anyone got any ideas on this issue.

EDIT 1: PHP Source File http://beta.dean.technology/proxySource.txt

¿Fue útil?

Solución

Make sure you emit the headers on the OPTIONS pre-flight request. You don't need to emit it on GET or POST requests, you're allowed to emit them but it doesn't do anything.

Before the actual POST request is made your browser will issue a pre-flight request that is an OPTIONS request.

if ($_SERVER['REQUEST_METHOD'] === "OPTIONS") {
    // emit CORS headers
    exit;
} else {
    // regular request
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top