jsonp(JSON with Padding)是一种使用模式,可以实现跨域获取数据,原理是基于由于script标签不受限于同源策略,script标签可以通过src属性请求到其他服务器上的数据
浏览器同源策略:在当前网页中,若想到发送一个请求,请求url必须满足 协议,域名,端口 三者相同,才能得到正常响应,否则属于跨域请求,浏览器会限制跨域请求。
jsonp是实现跨域一种的方式。
一、服务器端代码实现
let express = require('express');
var http = require('http');
let port = 1013;
let app = new express();
app.get('/say', function (req, res) {
let { cb } = req.query;
res.write(`${cb}('hello,jsonp')`);
res.end();
});
app.listen(port, () => {
try {
console.log(`http server start listening at http://localhost:${port}`);
} catch (error) {}
});
二、客户端代码1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body></body>
</html>
<script>
function sayHello(data) {
alert(data)
}
</script>
<script type="text/javascript" src="http://localhost:1013/say?cb=sayHello"></script>
三、客户端代码2
使用自定义jsonp函数,效果同上
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body></body> </html> <script> const callback = 'sayHello' function jsonp(p) { let { url, params, cb } = p; return new Promise((resolve, reject) => { let script = document.createElement('script'); //定义回调函数,服务器返回sayHello()执行时调用 window[cb] = function (data) { resolve(data); document.body.removeChild(script) }; params = { ...params, cb }; let arrs = []; for (const key in params) { arrs.push(`${key}=${params[key]}`); } script['src'] = `${url}?${arrs.join('&')}`; document.body.appendChild(script) }); } jsonp({ url: 'http://localhost:1013/say', params: { wd: 'jsonp' }, cb: callback, }).then((data) => { //callback console.log(data) }); </script>