目錄
正文
-
JSONP
優缺點:
JSONP優點是簡單兼容性好,可用於解決主流瀏覽器的跨域數據訪問的問題。缺點是僅支持get方法具有侷限性,不安全可能會遭受XSS攻擊。
實現原理:
- 聲明一個回調函數,其函數名(如show)當做參數值,要傳遞給跨域請求數據的服務器,函數形參爲要獲取目標數據(服務器返回的data)。
- 創建一個
<script>
標籤,把那個跨域的API數據接口地址,賦值給script的src,還要在這個地址中向服務器傳遞該函數名(可以通過問號傳參:?callback=show)。 - 服務器接收到請求後,需要進行特殊的處理:把傳遞進來的函數名和它需要給你的數據拼接成一個字符串,例如:傳遞進去的函數名是show,它準備好的數據是show(‘data’)。
- 最後服務器把準備的數據通過HTTP協議返回給客戶端,客戶端再調用執行之前聲明的回調函數(show),對返回的數據進行操作。
代碼:
後端:
const http = require('http');
const url = require('url');
const PORT = 8889;
// 創建一個 http 服務
const server = http.createServer((request, response) => {
// 獲取前端請求數據
const queryObj = url.parse(request.url, true).query;
console.log(queryObj);
// 這裏把前端傳來的 callback 字段作爲後端返回的回調函數的函數名稱
response.end(`${queryObj.callback}({name: '後臺返回的數據'})`);
});
server.listen(PORT, () => {
console.log('服務啓動成功!');
})
前端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSONP</title>
</head>
<body>
JSONP
</body>
<script>
function Jsonp(url, cb) {
this.callbackName = 'jsonp_' + Date.now();
this.cb = cb
this.url = url
this.init()
}
// 初始化方法 用於拼接 url
Jsonp.prototype.init = function() {
if(~this.url.indexOf('?')) {
this.url = this.url + '&callback=' + this.callbackName
} else {
this.url = this.url + '?callback=' + this.callbackName
}
this.createCallback()
this.createScript()
}
// 創建 script 標籤, src 取接口請求的url
Jsonp.prototype.createScript = function() {
var script = document.createElement('script')
script.src = this.url
var that = this;
script.onload = function() {
// 刪除標籤
// document.body.removeChild(script);
this.remove();
// 刪除 window 下定義的無用方法
delete window[that.callbackName]
console.log('that.callbackName: ', that.callbackName);
}
document.body.appendChild(script)
}
// 綁定回調函數
Jsonp.prototype.createCallback = function() {
window[this.callbackName] = this.cb
}
// 創建 jsonp 實例, 並指定回調函數
new Jsonp('http://localhost:8889/a', function(data) {
console.log(data)
})
</script>
</html>