JavaScript 无法访问我的查询 API
我使用 Google App Engine 构建了一个应用程序:
- 查询 URL(例如
http://myapp.appspot.com/query?name="SomeName"&start_date="2012-01-01"
) - 接收 JSON 响应。此 JSON 响应包含来自同一域中我自己的数据存储的数据。
- 使用该响应绘制图表。
app.yaml
配置具有以下几行:
- url: /.*
script: main.py
在 main.py
中,我分配了由类 处理的 URL
。query
>查询处理程序
如果我在线运行该应用程序,一切都很好。但是,如果我使用离线开发服务器运行应用程序,我将无法收到 JSON 响应。
离线测试时,我还将在线数据存储复制到离线开发服务器中。我可以确认它运行良好,因为我有其他脚本可以查询它并且它们运行良好。唯一的问题是 JavaScript 图表。
尝试的解决方案
- 如果我将查询 URL 更改为
http://localhost:8080/query?name="SomeName"&start_date="2011-01-01"
,图表将呈现良好。 - 如果我坚持查询云端的 URL
http://myapp.appspot.com/query?name="SomeName"&start_date="2012-01-01"
,我无法渲染图表。
目标
我希望能够随时查询云 URL,而不必将域更改为 localhost
。从长远来看,当我决定开放公共 API 时,这对我很有用。有办法做到这一点吗?或者这只是开发服务器的限制?
I built an app with Google App Engine that:
- Queries a URL (e.g.
http://myapp.appspot.com/query?name="SomeName"&start_date="2012-01-01"
) - Receives a JSON response. This JSON response contains data from my own datastore within the same domain.
- Plots a chart using that response.
The app.yaml
configuration has the following lines:
- url: /.*
script: main.py
Where in main.py
, I assigned the URL query
to be handled by the class QueryHandler
.
All is well and good if I run the app online. However, I cannot receive a JSON response if I run the app using the offline development server.
When testing offline, I also duplicate my online datastore into the offline development server. I can confirm that it works well because I have other scripts that query into it and they work fine. The only problem is the JavaScript chart.
Attempted solutions
- If I change the query URL to
http://localhost:8080/query?name="SomeName"&start_date="2011-01-01"
, the chart renders fine. - If I insist on the querying the URL on the cloud
http://myapp.appspot.com/query?name="SomeName"&start_date="2012-01-01"
, I cannot render the chart.
Objective
I'd like to be able to query the cloud URL at all times, without having to change the domain to localhost
. This will be useful to me in the long run when I decide to open up a public API. Is there a way to do that? Or is this just a limitation on the development server?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 JavaScript 应该始终从加载它的位置查询回服务器。
使用
window.location.hostname
和window.location.port
来获取主机和主机名。源服务器的端口。Your javascript should always query back to the server from where it was loaded.
Use
window.location.hostname
andwindow.location.port
to get the host & port of origin server.由于您显然控制着生成 JSON 的服务器,因此您可以通过提供 JSONP 来解决SOP这并不是什么额外的工作。
只需检查回调参数并将输出包装在作为回调传递的函数名称中。请参阅 JSONP。
As you are apparently in control of the server who generates the JSON, you might workaround SOP by serving JSONP which is not much additional work.
Just check for a callback parameter and wrap your output within the fucntionname passed as callback. See JSONP.