一、JSONP
<script src=""></script>
基本原理就是通過動態創建 script 標籤,然後利用 src 屬性進行跨域(後端用回調函數名稱包裹數據進行返回即可),但是要注意 JSONP 只支持 GET 請求,不支持 POST 請求:
// 回調函數
function showData (result) {
// json 對象轉成字符串
$('#text').val(JSON.stringify(result));
}
$(document).ready(function () {
$('#btn').click(function () {
//向頭部輸入一個腳本,該腳本發起一個跨域請求
$('head').append('<script src="http://localhost:9090/student?callback=showData"><\/script>');
});
});
jQuery的JSONP請求
$(document).ready(function () {
$('#btn').click(function () {
$.ajax({
url: 'http://localhost:9090/student',
type: 'GET',
dataType: 'jsonp', // 指定服務器返回的數據類型
jsonpCallback: 'showData', // 也可以指定回調函數
success: function (data) {
// json對象轉成字符串
$('#text').val(JSON.stringify(data));
}
});
});
});
二、CORS 跨域資源共享
利用 nginx 或者 php、java 等後端語言設置允許跨域請求:
header('Access-Control-Allow-Origin: *'); // 允許所有來源訪問
header('Access-Control-Allow-Method: POST,GET'); // 允許訪問的方式
三、服務器代理
瀏覽器有跨域限制,但是服務器不存在跨域問題,所以可以由服務器請求所要域的資源再返回給客户端。
Nodejs做代理(eggjs)
async demo() {
const { ctx: {inputs} } = this;
// 第三方接口地址
const url = 'http://api.map.baidu.com/location/ip';
// 獲取第三方接口
const res = await this.ctx.curl(url, {
method: 'POST',
dataType: 'text',
data: inputs
});
// 返回數據
this.success({
data: res.data~~~~
});
}
四、Nginx 反向代理
在配置文件 nginx.conf 中添加以下配置:
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}