2014-09-25 199 views
0

我有一個API在服務器上獲取某個日期。允許我的API通過AJAX訪問

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); 
} 

它在通常的捲曲方法上工作正常。但我試圖在Angular.js上使用$ http來訪問它,它給我帶來了這個錯誤。

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.

正如你所看到的,我已經在函數中添加了標題。我也檢查了curl,並且在我調用api時連接了標題Access-Control-Allow-Origin。

有什麼我在這裏失蹤?

更多信息:這是通過正常捲曲返回給我的標題信息。

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

你可以檢查網絡響應的ajax調用,如果頭是真正設置? – 2014-09-25 09:58:04

+0

@johnSmith我該怎麼做? ...我在上面添加了迴應。 – 2014-09-25 09:58:46

+0

是您的ajax請求跨域?如果是這樣的話,你需要使用jsonp並將迴應包裝在提供的回調中(如果存在),以便在通過cURL訪問時不會出現亂碼,因此它可以正常工作 – martincarlin87 2014-09-25 10:04:51

回答

1

瀏覽器發出第一個飛行前的選項調用您的API,這是什麼觸發錯誤:Access-Control-Allow-Origin。你可以創建自己的API接受的所有選項請求一個端點,你必須也有設置的標頭就像崗位事件:

header('Access-Control-Allow-Origin: *'); 

,你還會收到的404未找到的狀態代碼。這意味着無法找到OPTIONS端點。

+0

所以我必須添加頭('訪問控制 - 允許 - 方法:GET,POST','OPTIONS');?您能否提供更多解釋? – 2014-09-26 01:12:50

+0

我想你上面發佈的那段代碼匹配一個端點 讓我們假設/事件與POST方法匹配你的功能 當你試圖做這個Ajax來自瀏覽器在接收到POST請求,您將在/ events上收到OPTIONS請求。 你在API中要做的是定義與以下函數匹配的OPTIONS/events端點: 'public function options_events(){ header('Access-Control-Allow-Origin:*'); }' – 2014-09-26 09:33:40

+0

看看這裏也是特定的角度: [選項角](http://stackoverflow.com/questions/21792759/confused-about-how-to-handle-cors-options-preflight-要求) – 2014-09-26 09:40:01

相關問題