【问题标题】:Failed to load http://127.0.0.1:8000/api/users: No 'Access-Control-Allow-Origin' header is present on the requested resource无法加载 http://127.0.0.1:8000/api/users:请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2017-12-29 15:24:16
【问题描述】:

当我想用 API Symfony 和 Angular js(前端)添加表单时,我遇到了这个错误,有人知道为什么吗?

无法加载http://127.0.0.1:8000/api/users:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:4200” 使用权。 AddUserComponent.html:16 ERROR 错误:尝试区分时出错 '服务器错误'。只允许使用数组和可迭代对象 在 DefaultIterableDiffer.webpackJsonp.../../../core/@angular/core.es5.js.DefaultIterableDiffer.diff (core.es5.js:6843) 在 NgForOf.webpackJsonp.../../../common/@angular/common.es5.js.NgForOf.ngDoCheck (common.es5.js:1691) 在 checkAndUpdateDirectiveInline (core.es5.js:10846) 在 checkAndUpdateNodeInline (core.es5.js:12341) 在 checkAndUpdateNode (core.es5.js:12284) 在 debugCheckAndUpdateNode (core.es5.js:13141) 在 debugCheckDirectivesFn (core.es5.js:13082) 在 Object.eval [as updateDirectives] (AddUserComponent.html:21) 在 Object.debugUpdateDirectives [as updateDirec

用户服务

 @Injectable()
    export class UserService {
      private uri= 'http://127.0.0.1:8000/api/users';
      constructor(private http: Http, private authenticationService: AuthService  
     ) {}
      addUser(user: User) {
            const  headers = new Headers();
            headers.append('content-type', 'application/json');
            headers.append('Authorization', 'Bearer ' + this.authenticationService.token);
            return this.http.post(this.uri, JSON.stringify(user), {headers : headers})
            .map(res => res.json()).catch(this.handelError);
          }

【问题讨论】:

  • 研究“CORS”,获得一些了解。控制跨站脚本攻击非常重要。

标签: angular rest api symfony


【解决方案1】:

这是 CORS 问题。 CORS 是在浏览器中实现的安全性。如果您使用 Angular,您可以通过创建 proxy.conf.json 文件来充当代理服务器来解决此问题。

{
  "/api*": {
    "target": "http://127.0.0.1:8000",

  },
    "changeOrigin": true
  }
}

然后修改 package.json 中的 npm start 命令如下

"start": "ng serve --proxy-config proxy.conf.json"

您可以在 this 链接上阅读更多相关信息

【讨论】:

  • 我编辑了 "target": "127.0.0.1:8000" 或 localhost:4200 因为我使用 symfony localhost:8000 和 angularjs localhost:4200 ? @santosh 辛格
  • 目标将是您的 api 127.0.0.1:8000/api
  • 我使用 ng server 或 npm start 运行? @santosh 辛格
  • @helen npm start
  • @helen : 奇怪!
【解决方案2】:

这是 CORS 问题。 CORS 是在浏览器中实现的安全性。

这意味着你不能向其他域或端口发出 HTTP 请求。

在您的情况下,您的应用程序在 localhost:4200 上运行,但您从 localhost:8000 请求。因此,这被浏览器阻止了。

出于开发目的,您可以使用angular-cli proxy,它允许您在 4200 端口上建立隧道。

对于生产用途,您应该在 CORS 安全标头中将您的服务器列入白名单,或者让您的 API 在同一主机上可用(例如将 /api 映射到您的后端)。

【讨论】:

    猜你喜欢
    • 2014-12-15
    • 2016-10-10
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    相关资源
    最近更新 更多