在前端開發及調試過程當中總能遇到瀏覽器報以下錯誤:html
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.前端
該錯誤由瀏覽器的同源策略(同ip,同端口,同協議視爲同一個域,一個域內的腳本僅僅具備本域內的權限,能夠理解爲本域腳本只能讀寫本域內的資源,而沒法訪問其它域的資源。這種安全限制稱爲同源策略。 )所引發的。jquery
解決方案ajax
1.CORS(Cross-Origin Resource Sharing)是W3C在05年提出的跨域資源請求機制,它要求當前域(常規爲存放資源的服務器)在響應報頭添加Access-Control-Allow-Origin標籤,從而容許指定域的站點訪問當前域上的資源。json
不過CORS默認只支持GET/POST這兩種http請求類型,若是要開啓PUT/DELETE之類的方式,須要在服務端在添加一個"Access-Control-Allow-Methods"報頭標籤跨域
2.JSONP瀏覽器
JSONP(JSON with Padding)是JSON的一種「使用模式」,主要是利用script標籤不受同源策略限制的特性,向跨域的服務器請求並返回一段JSON數據。安全
客戶端服務器
---------------------------------------------------------------jsonp
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>JSONP</title>
<script src="jq.js"></script>
</head>
<body>
<div></div>
<script>
$.ajax({
url:'http://127.0.0.1:1234/',
dataType:"jsonp", //告知jQ咱們走的JSONP形式
jsonpCallback:"abc", //callback名
success:function(data){
console.log(data)
}
});
</script>
</body>
</html>
-------------------------------------------------------------------------------
服務端
------------------------------------------------------------------------------
var http = require('http');
var urllib = require('url');
var data = {'name': 'vajoy', 'addr': 'shenzhen'};
http.createServer(function(req, res){
res.writeHead(200, { 'Content-type': 'text/plain'});
var params = urllib.parse(req.url, true);
//console.log(params);
if (params.query && params.query.callback) {
//console.log(params.query.callback);
var str = params.query.callback + '(' + JSON.stringify(data) + ')';//jsonp
res.end(str);
} else {
res.end(JSON.stringify(data));//普通的json
}
}).listen(1234)
--------------------------------------------------------------------------------
不過JSONP始終是無狀態鏈接,不能獲悉鏈接狀態和錯誤事件,並且只能走GET的形式。
http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html 參考博文