【问题标题】:blocked by CORS policy in ionic-5 angular被 ionic-5 angular 中的 CORS 策略阻止
【发布时间】:2020-06-14 16:22:09
【问题描述】:

我正面临这个错误,有人可以指导我吗? 我已经在 proxy.conf.json 中进行了配置 我在 user.service.ts 中设置了带有基本 url 的标题

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { map } from 'rxjs/operators';


@Injectable()
export class UserService {

    constructor(public http: Http) { }

    yaho() {
        const headers = new Headers();
        headers.append('Access-Control-Allow-Origin', '*');
        // headers.append('Access-Control-Allow-Credentials', 'true');
        headers.append('Access-Control-Allow-Headers', 'Content-Type');

        headers.append('Access-Control-Allow-Methods', 'GET, POST');


        headers.append('Content-Type', 'application/json');
        headers.append('appKey', '4d71e017-6896-477b-bb0d-93bb9e6d3224');
        const options = new RequestOptions({ headers });
        const baseURL = 'abx/gas.json';
        console.log('Base url---->' + baseURL);
        const url = 'localhost:8081/abx/gas.json';
        return this.http.get(url, options)
            .pipe(map(res => res.json()));
    }
}

【问题讨论】:

  • 错误:从源“localhost:8102”访问“localhost:8081/abx/gas.json”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问控制” -Allow-Origin' 标头存在于请求的资源上。
  • 我对 proxy.conf.json 文件做了一些改动 { "/api": { "target": "localhost:8081", "secure": false, "logLevel": "debug" } }

标签: android angular ionic5


【解决方案1】:

您必须将后端配置为接受 CORS,而不是前端

(您尝试添加的标头应添加到后端而不是角应用程序)

【讨论】:

  • 我可以知道确切的位置或任何文件
  • 取决于您使用的服务器,您如何为localhost:8102 提供服务?
  • 它的离子......!当我运行 ionic serve 时,它​​会在 8102 端口号上运行。
  • 对不起,我的意思是localhost:8081
  • 我在 8081 端口号上托管了 Thingworxs。在我的本地机器上
【解决方案2】:

您无法通过尝试在客户端中启用 CORS 来解决您的问题。这是http 的一般/基本特征,而不是特定于离子或角度的。如果您无法更改后端,则可以使用代理。

“Ionic CLI 引入了让代理服务器发出请求的功能,以解决您可能遇到的任何 CORS 问题。由于服务器正在向您的目的地发送新请求,因此不会有来源,因此没有需要 CORS”

here 和示例回购here 所述

我假设您是如何尝试处理 CORS 请求而不在后端启用它。

请注意,“CORS 仅在我们运行 ionic serve 或 ionic run -l 时运行或测试我们的应用时才会出现问题。”

设置代理:

  1. 在我们的 ionic.project 中设置代理
{
  "name": "proxy-example",
  "app_id": "",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://cors.api.com/api"
    }
  ]
}
  1. 替换要设置为代理服务器的端点 URL
  2. 运行ionic serve

除了这个“处理 CORS 问题的最简单方法是最终要求您的 API 提供商允许所有主机”

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 2020-01-15
    • 2021-04-18
    • 2019-09-15
    • 1970-01-01
    • 2020-09-11
    • 2021-04-16
    • 2018-02-26
    • 2019-11-19
    相关资源
    最近更新 更多