我们一般说的跨域,是在同源策略限制下,浏览器从一个域请求另一个域的资源。同源策略(SOP,Same origin policy)是浏览器的一种安全策略。也就是说,当浏览器打开A域后,在A域内如果需要访问B域的资源,如果B域不允许跨域访问,浏览器就会报禁止跨域的错误,而如果在A域中对B域的资源进行代理,浏览器 -> A域 -> 代理 -> B域
,就不会出现禁止跨域的错误。
同源指的是【协议+域名+端口】都相同,否则即使两个域名指向同一个IP,也不是同源。
同源策略主要限制了以下几种场景:
- Cookie、LocalStorage和IndexDB的无法读取
- DOM和JS对象无法获得
- AJAX请求不能发送
常见跨域场景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 域名不同(即使是主域和子域也属于跨域) http://www.google.com/a.js http://map.google.com/b.js
端口不同 http://192.168.0.10:8080 http://192.168.0.10:8090
协议不同 http://192.168.0.10:8080 https://192.168.0.10:8080
域名和对应IP http://www.tyival.com http://192.168.0.100
|
常见解决方案
- JSONP
- document.domain + ifame
- location.hash + iframe
- window.name + iframe
- postMessage
- 跨域资源共享
- nginx代理
- nodejs中间件代理
- WebSocket协议
1. JSONP
我们在工程中经常会遇到引入在线的css、js等资源的情况,这种跨域引用是通过script标签进行实现的,这说明script标签是允许跨域的。我们可以动态创建script,再请求一个带参网址,从而实现跨域,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| <script> var script = document.createElement('script'); script.type = 'text/javascript';
// 传参并指定回调执行函数为onBack script.src = 'http://www.domain.com:8080/login?user=admin&callback=onBack'; document.head.appendChild(script);
// 回调执行函数 function onBack(res) { // 此处可以获取到类似 {"status": true, "data": ""} 的结果 } </script>
|
从以上代码可以看到,JSONP有一个最大缺点——只能创建GET请求。
2. document.domain + iframe
此方案只适用于主域相同,子域不同的场景。主要原理是两个页面都用js强制设置document.domain为主域,就实现了同源。
1 2 3 4 5 6
| <iframe id="iframe" src="http://child.domain.com/b.html"></iframe> <script> document.domain = 'domain.com'; var user = 'admin'; </script>
|
1 2 3 4 5 6
| <script> document.domain = 'domain.com'; // 获取父窗口中变量,值为admin console.log(window.parent.user); </script>
|
3. location.hash + iframe
实现原理: a欲与b跨域相互通信,通过中间页c来实现。不同域之间利用iframe的location.hash传值,相同域之间通过js访问来通信。
具体实现:A域:a.html -> B域:b.html -> A域:c.html,a与b不同域只能通过hash值单向通信,b与c也不同域也只能单向通信,但c与a同域,所以c可通过parent.parent访问a页面所有对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe> <script> var iframe = document.getElementById('iframe');
// 向b.html传hash值 setTimeout(function() { iframe.src = iframe.src + '#user=admin'; }, 1000); // 开放给同域c.html的回调方法 function onCallback(res) { alert('data from c.html ---> ' + res); } </script>
|
1 2 3 4 5 6 7 8 9 10
| <iframe id="iframe" src="http://www.domain1.com/c.html" style="display:none;"></iframe> <script> var iframe = document.getElementById('iframe');
// 监听a.html传来的hash值,再传给c.html window.onhashchange = function () { iframe.src = iframe.src + location.hash; }; </script>
|
1 2 3 4 5 6 7 8
| <script> // 监听b.html传来的hash值 window.onhashchange = function () { // 再通过操作同域a.html的js回调,将结果传回 window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', '')); }; </script>
|
4. window.name + iframe
window.name属性的独特之处:name值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| var proxy = function(url, callback) { var state = 0; var iframe = document.createElement('iframe');
// 加载跨域页面 iframe.src = url;
// onload事件会触发2次,第1次加载跨域页,并留存数据于window.name iframe.onload = function() { if (state === 1) { // 第2次onload(同域proxy页)成功后,读取同域window.name中数据 callback(iframe.contentWindow.name); destoryFrame();
} else if (state === 0) { // 第1次onload(跨域页)成功后,切换到同域代理页面 iframe.contentWindow.location = 'http://www.domain1.com/proxy.html'; state = 1; } };
document.body.appendChild(iframe);
// 获取数据以后销毁这个iframe,释放内存;这也保证了安全(不被其他域frame js访问) function destoryFrame() { iframe.contentWindow.document.write(''); iframe.contentWindow.close(); document.body.removeChild(iframe); } };
// 请求跨域b页面数据 proxy('http://www.domain2.com/b.html', function(data){ alert(data); });
|
1 2 3 4
| <script> window.name = 'This is domain2 data!'; </script>
|
总结:通过iframe的src属性由外域转向本地域,跨域数据即由iframe的window.name从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操作。
5. postMessage
postMessage是HTML5 XMLHttpRequest Level 2中的API,且是为数不多可以跨域操作的window属性之一,它可用于解决以下方面的问题:
- 页面和其打开的新窗口的数据传递
- 多窗口之间消息传递
- 页面与嵌套的iframe消息传递
- 上面三个场景的跨域数据传递
用法:postMessage(data,origin)方法接受两个参数
data: html5规范支持任意基本类型或可复制的对象,但部分浏览器只支持字符串,所以传参时最好用JSON.stringify()序列化。
origin: 协议+主机+端口号,也可以设置为”*”,表示可以传递给任意窗口,如果要指定和当前窗口同源的话设置为”/“。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe> <script> var iframe = document.getElementById('iframe'); iframe.onload = function() { var data = { name: 'aym' }; // 向domain2传送跨域数据 iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com'); };
// 接受domain2返回数据 window.addEventListener('message', function(e) { alert('data from domain2 ---> ' + e.data); }, false); </script>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <script> // 接收domain1的数据 window.addEventListener('message', function(e) { alert('data from domain1 ---> ' + e.data);
var data = JSON.parse(e.data); if (data) { data.number = 16;
// 处理后再发回domain1 window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com'); } }, false); </script>
|
6. 跨域资源共享
通常只需要在服务端设置Access-Control-Allow-Origin为*即可,例如可以在SpringMVC拦截器里加入如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class CorsInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); httpServletResponse.setHeader("Access-Control-Max-Age", "3600"); httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, Origin, Content-Type, Accept, token, apikey"); return true; }
@Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
} }
|
但是,如果需要在跨域访问时,Request Header中带上Cookie信息,还需要进行如下设置:
前端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('post', 'http://www.domain2.com:8080/login', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send('user=admin');
xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); } };
|
1 2 3 4 5 6 7 8 9 10
| $.ajax({ ... xhrFields: { withCredentials: true }, crossDomain: true, ... });
|
后端
1 2 3 4
| response.setHeader("Access-Control-Allow-Origin", "http://www.domain.com:port");
response.setHeader("Access-Control-Allow-Credentials", "true");
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| var http = require('http'); var server = http.createServer(); var qs = require('querystring');
server.on('request', function(req, res) { var postData = '';
req.addListener('data', function(chunk) { postData += chunk; });
req.addListener('end', function() { postData = qs.parse(postData);
res.writeHead(200, { 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': 'http://www.domain1.com', 'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' });
res.write(JSON.stringify(postData)); res.end(); }); });
server.listen('8080'); console.log('Server is running at port 8080...');
|
7. nginx代理
1、 nginx配置解决iconfont跨域
浏览器跨域访问js、css、img等常规静态资源被同源策略许可,但iconfont字体文件(eot|otf|ttf|woff|svg)例外,此时可在nginx的静态资源服务器中加入以下配置。
1 2 3
| location / { add_header Access-Control-Allow-Origin *; }
|
2、 nginx反向代理接口跨域
跨域原理: 同源策略是浏览器的安全策略,不是HTTP协议的一部分。服务器端调用HTTP接口只是使用HTTP协议,不会执行JS脚本,不需要同源策略,也就不存在跨越问题。
实现思路:通过nginx配置一个代理服务器(域名与domain1相同,端口不同)做跳板机,反向代理访问domain2接口,并且可以顺便修改cookie中domain信息,方便当前域cookie写入,实现跨域登录。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #proxy服务器 server { listen 81; server_name www.domain1.com;
location / { proxy_pass http://www.domain2.com:8080; #反向代理 proxy_cookie_domain www.domain2.com www.domain1.com; #修改cookie里域名 index index.html index.htm;
# 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用 add_header Access-Control-Allow-Origin http://www.domain1.com; #当前端只跨域不带cookie时,可为* add_header Access-Control-Allow-Credentials true; } }
|
1 2 3 4 5 6 7 8
| var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('get', 'http://www.domain1.com:81/?user=admin', true); xhr.send();
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| var http = require('http'); var server = http.createServer(); var qs = require('querystring');
server.on('request', function(req, res) { var params = qs.parse(req.url.substring(2));
res.writeHead(200, { 'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' });
res.write(JSON.stringify(params)); res.end(); });
server.listen('8080'); console.log('Server is running at port 8080...');
|
8. Nodejs中间件代理跨域
node中间件实现跨域代理,原理大致与nginx相同,都是通过启一个代理服务器,实现数据的转发,也可以通过设置cookieDomainRewrite参数修改响应头中cookie中域名,实现当前域的cookie写入,方便接口登录认证。
非vue框架的跨域(2次跨域)
利用node + express + http-proxy-middleware搭建一个proxy服务器。
1 2 3 4 5 6 7 8
| var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('get', 'http://www.domain1.com:3000/login?user=admin', true); xhr.send();
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| var express = require('express'); var proxy = require('http-proxy-middleware'); var app = express();
app.use('/', proxy({ target: 'http://www.domain2.com:8080', changeOrigin: true,
onProxyRes: function(proxyRes, req, res) { res.header('Access-Control-Allow-Origin', 'http://www.domain1.com'); res.header('Access-Control-Allow-Credentials', 'true'); },
cookieDomainRewrite: 'www.domain1.com' }));
app.listen(3000); console.log('Proxy server is listen at port 3000...');
|
2、 vue框架的跨域(1次跨域)
利用node + webpack + webpack-dev-server代理接口跨域。在开发环境下,由于vue渲染服务和接口代理服务都是webpack-dev-server同一个,所以页面与代理接口之间不再跨域,无须设置headers跨域信息了。
webpack.config.js部分配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| module.exports = { entry: {}, module: {}, ... devServer: { historyApiFallback: true, proxy: [{ context: '/login', target: 'http://www.domain2.com:8080', changeOrigin: true, secure: false, cookieDomainRewrite: 'www.domain1.com' }], noInfo: true } }
|
9. WebSocket协议跨域
WebSocket protocol是HTML5一种新的协议。它实现了浏览器与服务器全双工通信,同时允许跨域通讯,是server push技术的一种很好的实现。
原生WebSocket API使用起来不太方便,我们使用Socket.io,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <div>user input:<input type="text"></div> <script src="./socket.io.js"></script> <script> var socket = io('http://www.domain2.com:8080');
socket.on('connect', function() { socket.on('message', function(msg) { console.log('data from server: ---> ' + msg); });
socket.on('disconnect', function() { console.log('Server socket has closed.'); }); });
document.getElementsByTagName('input')[0].onblur = function() { socket.send(this.value); }; </script>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| var http = require('http'); var socket = require('socket.io');
var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-type': 'text/html' }); res.end(); });
server.listen('8080'); console.log('Server is running at port 8080...');
socket.listen(server).on('connection', function(client) { client.on('message', function(msg) { client.send('hello:' + msg); console.log('data from client: ---> ' + msg); });
client.on('disconnect', function() { console.log('Client socket has closed.'); });
|
附:Java代理跨域请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
| package cn.o.utils;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.io.FileUtils; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.RedirectLocations; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils;
import java.io.File; import java.io.IOException; import java.net.URI;
public class HttpHelper {
public static JSONObject httpGet(String url){ HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = null; CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom(). setSocketTimeout(2000).setConnectTimeout(2000).build(); httpGet.setConfig(requestConfig);
try { response = httpClient.execute(httpGet, new BasicHttpContext());
if (response.getStatusLine().getStatusCode() != 200) {
System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url); return null; } HttpEntity entity = response.getEntity(); if (entity != null) { String resultStr = EntityUtils.toString(entity, "utf-8");
JSONObject result = JSON.parseObject(resultStr); if (result.getInteger("errcode") == 0) { return result; } else { System.out.println("request url=" + url + ",return value="); System.out.println(resultStr); int errCode = result.getInteger("errcode"); String errMsg = result.getString("errmsg");
} } } catch (IOException e) { System.out.println("request url=" + url + ", exception, msg=" + e.getMessage()); e.printStackTrace(); } finally { if (response != null) try { response.close(); } catch (IOException e) { e.printStackTrace(); } }
return null; } public static JSONObject httpPost(String url, Object data) { HttpPost httpPost = new HttpPost(url); CloseableHttpResponse response = null; CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom(). setSocketTimeout(2000).setConnectTimeout(2000).build(); httpPost.setConfig(requestConfig); httpPost.addHeader("Content-Type", "application/json");
try { StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8"); httpPost.setEntity(requestEntity); response = httpClient.execute(httpPost, new BasicHttpContext());
if (response.getStatusLine().getStatusCode() != 200) {
System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url); return null; } HttpEntity entity = response.getEntity(); if (entity != null) { String resultStr = EntityUtils.toString(entity, "utf-8");
JSONObject result = JSON.parseObject(resultStr); if (result.getInteger("errcode") == 0) { result.remove("errcode"); result.remove("errmsg"); return result; } else { System.out.println("request url=" + url + ",return value="); System.out.println(resultStr); int errCode = result.getInteger("errcode"); String errMsg = result.getString("errmsg"); } } } catch (IOException e) { System.out.println("request url=" + url + ", exception, msg=" + e.getMessage()); e.printStackTrace(); } finally { if (response != null) try { response.close(); } catch (IOException e) { e.printStackTrace(); } }
return null; } public static JSONObject uploadMedia(String url, File file){ HttpPost httpPost = new HttpPost(url); CloseableHttpResponse response = null; CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build(); httpPost.setConfig(requestConfig);
HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("media", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM, file.getName())).build(); httpPost.setEntity(requestEntity);
try { response = httpClient.execute(httpPost, new BasicHttpContext());
if (response.getStatusLine().getStatusCode() != 200) {
System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url); return null; } HttpEntity entity = response.getEntity(); if (entity != null) { String resultStr = EntityUtils.toString(entity, "utf-8");
JSONObject result = JSON.parseObject(resultStr); if (result.getInteger("errcode") == 0) { result.remove("errcode"); result.remove("errmsg"); return result; } else { System.out.println("request url=" + url + ",return value="); System.out.println(resultStr); int errCode = result.getInteger("errcode"); String errMsg = result.getString("errmsg"); } } } catch (IOException e) { System.out.println("request url=" + url + ", exception, msg=" + e.getMessage()); e.printStackTrace(); } finally { if (response != null) try { response.close(); } catch (IOException e) { e.printStackTrace(); } }
return null; } public static JSONObject downloadMedia(String url, String fileDir) { HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = null; CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build(); httpGet.setConfig(requestConfig);
try { HttpContext localContext = new BasicHttpContext();
response = httpClient.execute(httpGet, localContext);
RedirectLocations locations = (RedirectLocations) localContext.getAttribute(HttpClientContext.REDIRECT_LOCATIONS); if (locations != null) { URI downloadUrl = locations.getAll().get(0); String filename = downloadUrl.toURL().getFile(); System.out.println("downloadUrl=" + downloadUrl); File downloadFile = new File(fileDir + File.separator + filename); FileUtils.writeByteArrayToFile(downloadFile, EntityUtils.toByteArray(response.getEntity())); JSONObject obj = new JSONObject(); obj.put("downloadFilePath", downloadFile.getAbsolutePath()); obj.put("httpcode", response.getStatusLine().getStatusCode()); return obj; } else { if (response.getStatusLine().getStatusCode() != 200) {
System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url); return null; } HttpEntity entity = response.getEntity(); if (entity != null) { String resultStr = EntityUtils.toString(entity, "utf-8");
JSONObject result = JSON.parseObject(resultStr); if (result.getInteger("errcode") == 0) { result.remove("errcode"); result.remove("errmsg"); return result; } else { System.out.println("request url=" + url + ",return value="); System.out.println(resultStr); int errCode = result.getInteger("errcode"); String errMsg = result.getString("errmsg"); } } } } catch (IOException e) { System.out.println("request url=" + url + ", exception, msg=" + e.getMessage()); e.printStackTrace(); } finally { if (response != null) try { response.close(); } catch (IOException e) { e.printStackTrace(); } }
return null; } }
|