离子-受CORS政策禁止:没有“访问控制允许来源”

时间:2020-05-08 00:00:42

标签: angular typescript cors ionic4

我创建了一个Ionic应用程序,该应用程序已连接到API网站,出于保护目的,我已将我的网站连接到CloudFlare,然后启用了 Under Attack Mode (受攻击模式)请求,这些请求已完美发送而没有任何错误,但现在在控制台中显示一条错误消息:

Access to XMLHttpRequest at 'https://mywebsite.org/api/mobile/news?pageSize=15&currentPage=1&language=undefined' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

后端是烧瓶微服务,我也启用了cors角色,

cors.init_app(app, resources={r"https://mywebsite.org/api/*": {"origins": "https://mywebsite.org"}})

每次我从应用程序发送获取请求时,我都会在标头中添加一个Access-Control-Allow-Origin:

let headers = new HttpHeaders({
    "Access-Control-Allow-Origin":"https://mywebsite.org/",
    "origin":"https://mywebsite.org/"
});

@Injectable({
    providedIn: 'root'
})
export class DataApiService {

    private apiUrl: string = 'https://mywebsite.org/api';


    constructor(
    private http: HttpClient,
    private translate: TranslateService
    ) { }

    // Get news
    apiRequest(url: string, params?:any){

    const apiUri = `${this.apiUrl+url}`;

    if(params){
        params.language = this.translate.getDefaultLang();
    }

    return this.http.get(apiUri, { headers: headers, params: params }).pipe(
        delay(
        500
        ),
        map(
        (res:any) => {
            return res
        }
        )
    )
    }
}

请帮忙。

1 个答案:

答案 0 :(得分:1)

观看

https://ionicframework.com/docs/troubleshooting/cors

您必须添加主机而不是localhost(离子服务--host test.test.co)

然后转到本地磁盘

在此处移动C:\ Windows \ System32 \ drivers \ etc

然后修改您的主机文件

127.0.0.1 test.test.co

很抱歉不会英语

我希望它能帮助