如何处理跨域iframe文件上传json响应?
我正在构建一个文件上传 API。
基本上,用户必须将带有他/她的 api_key + 签名的文件发布到我的网络服务。然后我的 Web 服务会回复 JSON 响应。我想知道这个过程如何异步工作?
假设用户以将目标设置为 iframe 的形式 POST 请求。 JSON 响应将在其 iframe 上发送回用户,内容类型设置为“text/html”。它被设置为“text/html”而不是“application/json”,因为我想避免浏览器在 JSON 响应周围注入“pre”标签。无论如何,如果 iframe 和父窗口具有不同的域,用户如何读取 JSON 响应?将会出现跨域策略问题。
在这种情况下,动态创建“脚本”标签加上 JSONP 将不起作用,因为我需要 POST 才能上传。 JSONP 仅适用于 GET 请求。
I'm building an files upload API.
Basically, the user will have to POST the files with his/her api_key + signature to my web service. Then my web service replies back with a JSON response. I'm wondering how can this process work asynchronously?
Assuming that the user POST the request in a form setting the target to an iframe. The JSON response will be sent back to the user on his/her iframe with content type set as "text/html". It is set as "text/html" instead of "application/json" because I want to avoid having a "pre" tag injected by the browser around the JSON response. Anyway, how does the user read that JSON response if the iframe and the parent window have different domain? There is going to be a cross domain policy issue.
Dynamically create "script" tag plus JSONP won't work in this case because I need to POST in order to upload. JSONP only works with GET requests.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请查看此处的“上传”示例。它使用跨域消息传递将消息传递回上传页面,并使用easyXDM支持所有浏览器。
这篇文章解释了这一切是如何进行的作品!
Take a look at the 'Upload' example here. It uses Cross Domain messaging to pass the message back to the uploading page, and uses easyXDM to support all browsers.
This post explains how it all works!
由于同源策略,浏览器不允许主框架中的 JavaScript 从另一个域读取/访问 iframe 中的任何内容。在这种情况下,用户将不得不使用 easyXDM 或创建自己的代理——这里的代理是指用户必须在后端编写一些可以与您的 API 通信的代码,以便发布请求将直接发送到您的服务器,并且将从他们自己的代理获得响应。
Because of Same Origin Policy, browsers wont allow JavaScript in the main frame reading/accessing whatever content in iframe from another domain. In this case, the users will have to use easyXDM or create their own proxy -- by proxy here i mean users will have to write some code on their backend that can communicate with your API such that a post request will go directly to your server, and a get response will get from their own proxy.