【问题标题】:I am getting error:(Cross-Origin Request Blocked) angular 2 ionic 2我收到错误消息:(Cross-Origin Request Blocked)angular 2 ionic 2
【发布时间】:2017-11-21 14:18:55
【问题描述】:

我收到以下错误: 跨域请求被阻止:同源策略不允许读取位于http://localhost/index.json 的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决。

我在下面给出的是我的代码。 任何机构都可以帮助我解决这个问题。

import { Injectable } from '@angular/core';
    import { Http ,Response} from '@angular/http';
    import 'rxjs/add/operator/map';

    @Injectable()
    export class WebserviceProvider {

      constructor(public http: Http) {

        console.log('Hello WebserviceProvider Provider');

      }

     getUser() {

        return this.http.get('http://localhost/index.json')
        .map((res:Response) => res.json());
      }

    }

【问题讨论】:

  • 但我正在使用下面的网址。 conduit.productionready.io/api/profiles/eric。任何人都可以帮助我使用以下网址localhost/index.json
  • 只需使用 Chrome 扩展程序:chrome.google.com/webstore/detail/allow-control-allow-origi/… 这样您就可以允许 CORS。
  • OK haseoh,但是我使用下面的 url 它没有出现 myip/get_emp.php?action=getdetails 以及如何使用本地 url?
  • 嗨 Haseoh,我在请求输出下使用 chrome 高级休息客户端,但是当我在 ionic this.http.get 中使用它时不起作用。显示错误“跨域请求被阻止:同源策略不允许读取myip/index.json 的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决。"
  • 据我所知,您使用的网址错误。您不能指向 localhost,当您从 .json 获取数据时,您应该像这样指向 .json 的目录:'assets/index.json'.

标签: angular


【解决方案1】:

您不能将您的 http.get 网址指向 localhost。您正在使用 .json 文件,而不是外部 API。这意味着,您必须将 .json 文件放入 assets 文件夹并更改:

return this.http.get('http://localhost/index.json')
.map((res:Response) => res.json());

到这里:

return this.http.get('assets/index.json')
.map((res:Response) => res.json());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2021-08-08
    • 2016-04-11
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    相关资源
    最近更新 更多