问题
I have an API that fetches some date on the server.
public function post_events()
{
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$city = Input::post('city','all');
$c = Model_chart::format_chart($city);
return $this->response($c);
}
It works fine on usual curl methods. But I am trying to access it using $http on Angular.js and it gets me this error.
XMLHttpRequest cannot load http://event.deremoe.com/vendor/events.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://app.event.chart' is therefore not allowed access.
As you can see I already add the headers in the function. I also checked on curl and the header Access-Control-Allow-Origin is attached when I call the api.
Is there something I am missing here?
More Info: Here's the header information that is returned to me via normal curl.
Remote Address:104.28.19.112:80
Request URL:http://event.deremoe.com/vendor/events.json
Request Method:OPTIONS
Status Code:404 Not Found
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:event.deremoe.com
Origin:http://app.event.chart
Referer:http://app.event.chart/
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
Response Headersview source
CF-RAY:16f687416fe30c35-SEA
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Thu, 25 Sep 2014 10:27:17 GMT
Server:cloudflare-nginx
Set-Cookie:__cfduid=d1a9e4283faacc0a2b029efef586b6b931411640837342; expires=Mon, 23-Dec-2019 23:50:00 GMT; path=/; domain=.deremoe.com; HttpOnly
Transfer-Encoding:chunked
X-Powered-By:PHP/5.4.30
回答1:
The browser makes first a pre-flight options call to your api and this is what it triggers the error: Access-Control-Allow-Origin
. You can create an endpoint on your api that accepts all the OPTIONS request and you have also to set the headers there like on the post events:
header('Access-Control-Allow-Origin: *');
The Status Code that you also receive is 404 Not Found. That means that is not able to find an OPTIONS endpoint.
来源:https://stackoverflow.com/questions/26035638/allow-my-api-to-be-access-via-ajax