使用 Angular JS、cors 调用 symfony 2 rest api

Call symfony 2 rest api with Angular JS, cors

我正在使用 angularJS 在 symfony 2 中调用 restfull API。

我的 angularJS 应用 url 是 angular.me.dev 我的 symfony2 api url 是 api.me.dev

我跟着this tutorial让我安心了api。

问题是当我尝试调用这个 api

$http.({
    method: 'GET',
    url: 'http://api.me.dev/api/articles',
    headers: {
        'Authorization': 'Bearer ' + token
    }
})

发生错误:(此处为 google chrome):

XMLHttpRequest cannot load http://api.me.dev/api/articles. Response for preflight has invalid HTTP status code 405

(以及在 firefox 上):

The Same Origin Policy disallows reading the remote resource

我发现了什么?

然后我决定允许 headers, origin, ... 在我的服务器上是这样的:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Methods "PUT, DELETE, POST, GET, OPTIONS"
Header always set Access-Control-Allow-Headers "*"

无变化

我加到AngularJS

#coffee script
app.config ['$httpProvider', ($httpProvider) ->
    $httpProvider.defaults.useXDomain = true
    delete $httpProvider.defaults.headers.common['X-Requested-With']
]

然后我决定在我的 symfony api 中安装 NelmioCorsBundle,但我没有看到任何变化。

最后,我注意到通话有效

$http.({
    method: 'GET',
    url: 'http://api.me.dev/api/articles',
})

这里调用 return 401 响应(很好,我需要登录)

$http.({
    method: 'GET',
    url: 'http://api.me.dev/public/api/users',
})

我这里有一个电话不需要授权,可以。 我发现只有当我删除 headers 时它才有效,当我有任何 headers (例如 content-type 或授权)时发生错误。

谁能帮帮我?谢谢!

好吧,我的错。

我说 NelmioCors 似乎不起作用,但我做错了什么。

我再次尝试使用 nelmio cors bundle,使用这个配置。

nelmio_cors:
    paths:
        '^/':
            allow_origin: ['http://angular.me.dev']
            allow_headers: ['Authorization', 'X-Requested-With', 'Content-Type', 'Accept', 'Origin', 'X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
            max_age: 3600

有效! NelmioCorsBundle 解决了这个问题。

https://github.com/nelmio/NelmioCorsBundle