我在heroku上有一个rails应用程序,它通过API提供数据。这些数据看起来像......
[{"created_at":"2014-02-20T17:22:02Z","id":1,"name":"Joe Rogan","twitter":"@joerogan","updated_at":"2014-02-20T17:22:02Z"},{"created_at":"2014-02-20T17:22:11Z","id":2,"name":"Kristen Schaa","twitter":"@kchalithis","updated_at":"2014-02-20T17:22:11Z"},{"created_at":"2014-02-20T17:29:10Z","id":3,"name":"Casey Grim","twitter":"@aCoupleofN3rds","updated_at":"2014-02-20T17:29:16Z"}]
我下拉了Ember Start Kit并修改了它以使用这样的代码从我的API中提取数据...
App.Person.adapter = Ember.RESTAdapter.create();
App.Person.url = "http://myapp.herokuapp.com/api/v1/shots?api_key=12d2d06fb2f6a786ac75b32625cf83a1";
App.Person.collectionKey = "people";
<script type="text/x-handlebars" id="index">
<ul>
{{#each item in model}}
<li>{{item.name}}</li>
{{/each}}
</ul>
</script>
我以为我可以像这样开始镀铬......
google-chrome --disable-web-security
让它仅用于测试,但这不起作用。
另外,听起来我需要使用jsonp而不是json?但不确定如何在ember(或其他任何地方)实现。任何帮助赞赏。感谢名单!
在我的rails应用中过滤之前添加:cors_set_access_control_headers。看起来像......
module Api
module V1
class ShotsController < ApplicationController
before_filter :cors_set_access_control_headers
...
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
end
......但仍然收到错误
XMLHttpRequest cannot /api/v1/shots?api_key=d26da3938adc5f3c8604256194c18501.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
...如果我发出一个curl来查看标题,我看到Access Controll设置为* ...
me@me-E6530:~$ curl -v http://myapp.herokuapp.com/api/v1/shots?api_key=12d2d06fb2f6a786ac75b32625cf83a1
* About to connect() to myapp.herokuapp.com port 80 (#0)
* Trying 54.243.169.60... connected
> GET /api/v1/shots?api_key=12d2d06fb2f6a786ac75b32625cf83a1 HTTP/1.1
> User-Agent: curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: myapp.herokuapp.com
> Accept: */*
>
< HTTP/1.1 200 OK
< Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
< Access-Control-Allow-Methods: POST, PUT, DELETE, GET, OPTIONS
< Access-Control-Allow-Origin: *
< Access-Control-Request-Method: *
答案 0 :(得分:0)
Ember希望以下列格式回复:
{
people: [
{
id: 1,
name: "John Doe"
},
{
id: 2,
name: "Jane Doe"
}
]
}
如果他们在不同的域名,您可能需要enable CORS。