1.什么是跨域?
是浏览器的一种安全策略。当浏览器的某个页面要访问的服务器地址,跟该页面的地址,存在协议,域名,端口号任一不相同时,浏览器视为跨域访问。
2.如何实现跨域?跨域的技术有哪些?
- 图像ping
- jsonp跨域
- CORS(跨域资源共享)需要后端同志设置响应头:Access-Control-Allow-Origin
- NGINX代理
- websocket协议跨域
3. 先看下jsonp跨域
-
首先是利用script标签的src属性来实现跨域。
-
通过将前端方法作为参数传递到服务器端,远程服务端通过调用指定的函数并传入参数来实现传递参数,将fn(response)传递回客户端。
如图:
-
由于使用script标签的src属性,因此只支持get方法。
上面图的实例如下:
前端代码:
function jsonp(req){
var script = document.createElement('script');
var url = req.url + '?callback=' + req.callback.name;
script.src = url;
document.getElementsByTagName('body')[0].appendChild(script);
}
function hello(res){
console.log('hello1111 ' + res.data);
}
jsonp({
url : 'http://localhost:3000/func',
callback : hello
});
后端服务器代码:
app.get('/func', function (req, res) {
if(req.query.callback){
console.log(req.query.callback);
var str = req.query.callback + '(' + JSON.stringify(data) + ')';
res.end(str);
} else {
res.end();
}
});
结果: