|
26 | 26 |
|
27 | 27 | 简单来说,只有当协议,域名,端口号相同的时候才算是同一个域名,否则,均认为需要做跨域处理。
|
28 | 28 |
|
29 |
| - |
| 29 | + |
30 | 30 |
|
31 | 31 | ## 跨域方法
|
32 | 32 |
|
@@ -74,9 +74,9 @@ console.log('启动服务,监听 127.0.0.1:3000');
|
74 | 74 | ```html
|
75 | 75 | // jsonp/index.html
|
76 | 76 | <script>
|
77 |
| - function jsonpCallback(data) { |
78 |
| - alert('获得 X 数据:' + data.x); |
79 |
| - } |
| 77 | + function jsonpCallback(data) { |
| 78 | + alert('获得 X 数据:' + data.x); |
| 79 | + } |
80 | 80 | </script>
|
81 | 81 | <script src="http://127.0.0.1:3000?callback=jsonpCallback"></script>
|
82 | 82 | ```
|
@@ -108,7 +108,7 @@ yarn jsonp
|
108 | 108 |
|
109 | 109 | 打开浏览器访问 ```localhost:8080``` 即可看到获取到的数据。
|
110 | 110 |
|
111 |
| - |
| 111 | + |
112 | 112 |
|
113 | 113 | 至此,通过 JSONP 跨域获取数据已经成功了,但是通过这种方式也存在着一定的优缺点:
|
114 | 114 |
|
@@ -169,7 +169,7 @@ console.log('启动服务,监听 127.0.0.1:3000');
|
169 | 169 |
|
170 | 170 | 然后我们执行命令:```yarn cors``` 打开浏览器访问 ```localhost:3000``` 即可看到效果:
|
171 | 171 |
|
172 |
| - |
| 172 | + |
173 | 173 |
|
174 | 174 | 成功的关键在于 Access-Control-Allow-Origin 是否包含请求页面的域名,如果不包含的话,浏览器将认为这是一次失败的异步请求,将会调用 xhr.onerror 中的函数。
|
175 | 175 |
|
@@ -222,7 +222,7 @@ console.log('启动服务,监听 127.0.0.1:3000');
|
222 | 222 |
|
223 | 223 | 启动服务 ```yarn proxy``` 并访问 ```http://localhost:3000/topics``` 即可看到效果:
|
224 | 224 |
|
225 |
| - |
| 225 | + |
226 | 226 |
|
227 | 227 | 跨域请求成功。纯粹的获取跨域获取后端数据的请求的方式已经介绍完了,另外介绍四种通过 iframe 跨域与其它页面通信的方式。
|
228 | 228 |
|
@@ -291,7 +291,7 @@ data.html 收到消息后通过 parent.location.hash 值来修改 index.html 的
|
291 | 291 |
|
292 | 292 | 之后启动服务 ```yarn hash```,即可在 ```localhost:8080``` 下观察到:
|
293 | 293 |
|
294 |
| - |
| 294 | + |
295 | 295 |
|
296 | 296 | 当然这种方法存在着诸多的缺点:
|
297 | 297 |
|
@@ -346,11 +346,11 @@ window.location = "http://www.baidu.com"
|
346 | 346 |
|
347 | 347 | 但是由于 index.html 页面与该页面 iframe 的 src 如果不同源的话,则无法操作 iframe 里的任何东西,所以就取不到 iframe 的 name 值,所以我们需要在 data.html 加载完后重新换个 src 去指向一个同源的 html 文件,或者设置成 'about:blank;' 都行,这时候我只要在 index.html 相同目录下新建一个 proxy.html 的空页面即可。如果不重新指向 src 的话直接获取的 window.name 的话会报错:
|
348 | 348 |
|
349 |
| - |
| 349 | + |
350 | 350 |
|
351 | 351 | 之后运行 ```yarn name``` 即可看到效果:
|
352 | 352 |
|
353 |
| - |
| 353 | + |
354 | 354 |
|
355 | 355 | ## 6.postMessage
|
356 | 356 |
|
@@ -392,7 +392,7 @@ postMessage 是 HTML5 新增加的一项功能,跨文档消息传输(Cross Doc
|
392 | 392 |
|
393 | 393 | 启动服务:```yarn postMessage``` 并打开浏览器访问:
|
394 | 394 |
|
395 |
| - |
| 395 | + |
396 | 396 |
|
397 | 397 | 对 postMessage 感兴趣的详细内容可以看看教程:
|
398 | 398 |
|
@@ -469,11 +469,10 @@ http {
|
469 | 469 |
|
470 | 470 | 启动服务 ```yarn domain``` 访问浏览器即可看到效果:
|
471 | 471 |
|
472 |
| - |
| 472 | + |
473 | 473 |
|
474 | 474 | ## 总结:
|
475 | 475 |
|
476 | 476 | 前面七种跨域方式我已经全部讲完,其实讲道理,常用的也就是前三种方式,后面四种更多时候是一些小技巧,虽然在工作中不一定会用到,但是如果你在面试过程中能够提到这些跨域的技巧,无疑在面试官的心中是一个加分项。
|
477 | 477 |
|
478 | 478 | 上面阐述方法的时候可能有些讲的不明白,希望在阅读的过程中建议你跟着我敲代码,当你打开浏览器看到结果的时候,你也就能掌握到这种方法。
|
479 |
| - |
0 commit comments