RESTful架構是目前比較流行的一種互聯網軟件架構,在此架構之下的瀏覽器前端和手機端能共用后端接口。
但是涉及到js跨域調用接口總是很頭疼,下邊就跟着chrome的報錯信息一起來解決一下。
假設:前端域名為front.ls-la.me
,后端域名為api.ls-la.com
。前端需要訪問的接口為http://api.ls-la.com/user/info.json
,需要用GET方式訪問。
現在,用Ajax向后端發送請求,得到第一個錯誤。(cors跨域的寫法參考:http://blog.csdn.net/fdipzone/article/details/46390573)
錯誤1:
XMLHttpRequest cannot load http://api.ls-la.com/user/info.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://api.ls-la.com' is therefore not allowed access.
提示響應頭沒有Access-Control-Allow-Origin
這一項,谷歌得知需要在服務器指定哪些域名可以訪問后端接口,設定之:
header('Access-Control-Allow-Origin: http://front.ls-la.me'); // 如果你不怕扣工資可以這么設:header('Access-Control-Allow-Origin: *');
再次發送請求,又報錯。
錯誤2:
XMLHttpRequest cannot load http://api.ls-la.com/user/info.json. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.
意思是ajax頭信息中有X-Requested-With
這一字段,后端不允許。那就讓允許吧:
header('Access-Control-Allow-Headers: X-Requested-With');
好了,這下不報錯了,但是仔細分析請求過程,發現瀏覽器向接口地址發送了兩個請求,第一個是OPTIONS
方式,第二個才是GET
方式。
這里的第一個請求叫做“Preflight Table Request(預檢表請求,微軟這么翻譯的,不知道對不對)”。這個請求是在跨域的時候瀏覽器自行發起的,作用就是先請求一下看看服務器支不支持當前的訪問。如果不支持,就會報之前所列的錯誤;如果支持,再發送正常的GET請求,返回相應的數據。
但是每個請求之前都要這么OPTIONS一下,作為典型處女座表示非常不能忍。需要告訴瀏覽器你搞一下是個意思,老這么搞就沒意思了:
// 告訴瀏覽器我支持這些方法(后端不支持的方法可以從這里移除,當然你也可以在后邊加上OPTIONS方法。。。) header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE'); // 告訴瀏覽器我已經記得你了,一天之內不要再發送OPTIONS請求了 header('Access-Control-Max-Age: ' . 3600 * 24);
好了,事情至此告一段落。
才怪!
突然有一天測試妹子跑來跟你說網站記不住用戶的狀態,一檢查發現跨域的時候cookie失效了。
錯誤3:
js在發送跨域請求的時候請求頭里默認是不帶cookie的,需要讓他帶上:
1 // js 2 var xhr = new XMLHttpRequest(); 3 xhr.open('GET', 'http://api.ls-la.com/user/info.json'); 4 xhr.withCredentials = true; 5 xhr.onload = onLoadHandler; 6 xhr.send(); 7 8 // jQuery 9 $.ajax({ 10 url: 'http://api.ls-la.com/user/info.json', 11 xhrFields: { 12 withCredentials: true 13 }, 14 crossDomain: true, 15 }); 16 17 // Angular 三選一 18 $http.post(url, {withCredentials: true, ...}) 19 $http({withCredentials: true, ...}).post(...) 20 app.config(function ($httpProvider) { 21 $httpProvider.defaults.withCredentials = true; 22 }
總之就是要在xhr里設置一下withCredentials = true
,然后跨域請求就能帶上cookie了。注意這里的cookie遵循同源策略,也就是后端發送的cookie也是屬於域名api.ls-la.com
的。
發送一個帶cookie的post請求,依舊報錯:
錯誤4:
XMLHttpRequest cannot load http://api.ls-la.com/user/info.json. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
跟上邊那個X-Requested-With
報錯一樣,頭信息不允許,后端改下:
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
再來,還是報錯:
錯誤5:
XMLHttpRequest cannot load http://api.ls-la.com/user/info.json. Response to preflight request doesn't pass access control check: Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://front.ls-la.me' is therefore not allowed access.
提示很明顯,后端代碼加一行,允許攜帶cookie訪問:
// 允許前端帶cookie訪問 header('Access-Control-Allow-Credentials: true');
總結
在后端程序加載前執行以下函數,避免OPTIONS請求浪費系統資源和數據庫資源。
function cors_options() { header('Access-Control-Allow-Origin: http://front.ls-la.me'); header('Access-Control-Allow-Credentials: true'); if('OPTIONS' != $_SERVER['REQUEST_METHOD']) return; header('Access-Control-Allow-Headers: X-Requested-With, Content-Type'); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE'); header('Access-Control-Max-Age: ' . 3600 * 24); exit; }
參考:
預檢表請求
Cross-Origin Resource Sharing
Angular通過CORS實現跨域方案 注意這里的[CORS的分類]一節。