开发者

Same origin issue (file upload)

开发者 https://www.devze.com 2023-02-28 23:26 出处:网络
The client is on domain foo.com and needs to upload (send POST XMLHttpRequest) to upload.foo.com. This is restricted because of the same origin policy.

The client is on domain foo.com and needs to upload (send POST XMLHttpRequest) to upload.foo.com.

This is restricted because of the same origin policy.

However, the work around that I managed to come up with is, to dynamically create iframe on foo.com opening upload.foo.com and append the JavaScript code which executes the POST request from upload.foo.com like this: iframe.onLoad [..]

(a=(b=doc)
.createElement('script'))
.src='http://foo.com/upload.php?'+Math.random(),
b.body.appendChild(a);
void(0);

Now, to me this seems redundant: if the later is possible, my logic tells me that the former should be possible as well. Is it?

-- update

I have just noticed that there is file on the sub domain containing this:

<?xml version="1.0" ?> 
<cross-domain-poli开发者_JAVA百科cy>
<allow-access-from domain="*" />
<allow-access-from domain="*.foo.com" secure="false" /> 
</cross-domain-policy>

Can I use it somehow to my advantage?


XMLHttpRequest is not sensitive to document.domain because the object requires mutual opt-in for security reasons, and XHR has no way of knowing what the target might want the document.domain value to be set to. In order for SiteA to interact with the DOM of a site on SiteB, both sites must share a common private domain suffix, and both must opt-in to the communication by setting document.domain to their common suffix.

Your cross-domain policy file doesn't actually make a lot of sense (as it opts-in everything, and then a subset of everything) but it's used for Flash, not XHR (which uses CORS).


I don't think it's possible to simplify this, but if it seems inelegant to you, there are simpler ways to use cross-origin JS.

Indeed, this is almost exactly what jQuery does if you try to send a request using jsonp. Wikipedia for JSONP
(Along with several other ways to bypass the same-origin restriction)

I don't know if this is what you're asking about, but in the name of maintainability, I would advise that you use the jQuery approach.

You need to set dataType: 'jsonp' and you're all set. You can optionally set the parameter "callback=?"(look at the docs).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号