JavaScript同源策略 - 它如何应用于不同的子域? [英] JavaScript Same Origin Policy - How does it apply to different subdomains?

查看:166
本文介绍了JavaScript同源策略 - 它如何应用于不同的子域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同源策略如何适用于以下两个域?



http://server1.MyDomain.com



http://server2.MyDomain.com



如果从server2中检索内容,我可以在server1上托管的页面上运行JS吗?< script> $ c>标签,但异步请求呢?如果我将脚本从server2下载到server1上托管的页面上该怎么办?我可以使用脚本与server2上的服务进行异步通信吗?

解决方案

您只能使用<在不同子域之间包含脚本< script> 代码,因为它免于政策。



使用 http: //www.example.com/dir/page.html 作为来源(来自维基百科):

 比较网址结果原因
--------- -------------------------------------------------- ----------------------------------
http://www.example.com/dir/ page.html成功相同的协议和主机
http://www.example.com/dir2/other.html成功相同的协议和主机
http://www.example.com:81/dir2/ other.html失败相同的协议和主机但不同的端口
https://www.example.com/dir2/other.html失败不同的协议
http://en.example.com/dir2/other.html失败不同的主机
http://example.com/dir2/other.html失败不同的主机(需要完全匹配)
http://v2.www.example.com/dir2/other.html失败不同主机(需要完全匹配)

更新:


我是否可以使用该脚本与
异步通信
server2上的服务?


是的,您可以使用 JSONP ,利用< script> 标签的开放政策从其他来源检索JSON 。



您可能还想考虑使用反向代理,如下面的Stack Overflow帖子所示:




How does the Same Origin Policy apply to the following two domains?

http://server1.MyDomain.com

http://server2.MyDomain.com

Can I run JS on a page hosted on server1, if the content is retreived from server2?

edit according to Daniel's answer below, I can include scripts between different subdomains using the <script> tag, but what about asynchronous requests? What if I download a script from server2 onto the page hosted on server1. Can I use the script to communicate asynchronously with a service on server2?

解决方案

You can only include scripts between different subdomains using the <script> tag, as it is exempt from the policy.

Using http://www.example.com/dir/page.html as source (from Wikipedia):

Compared URL                               Outcome  Reason
---------------------------------------------------------------------------------------------
http://www.example.com/dir/page.html       Success  Same protocol and host
http://www.example.com/dir2/other.html     Success  Same protocol and host
http://www.example.com:81/dir2/other.html  Failure  Same protocol and host but different port
https://www.example.com/dir2/other.html    Failure  Different protocol
http://en.example.com/dir2/other.html      Failure  Different host
http://example.com/dir2/other.html         Failure  Different host (exact match required)
http://v2.www.example.com/dir2/other.html  Failure  Different host (exact match required)

UPDATE:

Can I use the script to communicate asynchronously with a service on server2?

Yes, you can with JSONP, which takes advantage of the open policy for <script> tags to retrieve JSON from other origins.

You may also want to consider using a reverse proxy, as desribed in the following Stack Overflow post:

这篇关于JavaScript同源策略 - 它如何应用于不同的子域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆