【问题标题】:Call symfony 2 rest api with Angular JS, cors使用 Angular JS、cors 调用 symfony 2 rest api
【发布时间】:2016-01-31 09:02:55
【问题描述】:

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

我的 angularJS 应用程序网址是 angular.me.dev 我的 symfony2 api url 是 api.me.dev

我关注this tutorial 来制作我的restfull api。

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

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

发生错误:(在谷歌浏览器上):

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

(在火狐上):

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',
})

这里调用返回 401 响应(很好,我需要记录)

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

我有一个电话不需要授权,它可以工作。 我发现只有当我删除标题时它才有效,并且当我有任何标题(例如内容类型或授权)时发生错误。

谁能帮帮我?谢谢!

【问题讨论】:

    标签: angularjs api symfony cross-domain cors


    【解决方案1】:

    好吧,我的错。

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

    我再次尝试使用 nelmio cors 捆绑包,使用此配置。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-21
      • 2019-11-02
      • 2017-01-30
      • 2018-04-08
      • 2023-03-25
      • 1970-01-01
      • 2020-09-01
      • 2015-08-01
      相关资源
      最近更新 更多