在ionic-5角度被CORS政策阻止 [英] blocked by CORS policy in ionic-5 angular
问题描述
我正遇到此错误,有人可以同样指导我吗?我已经在proxy.conf.json中进行了配置我在user.service.ts
I am facing this error, can someone please guide me for the same. I have made configuration in proxy.conf.json I have set header with base url in user.service.ts
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()));
}
}
推荐答案
您无法通过尝试在客户端中启用CORS来解决问题.这是 http 的常规/基本功能特定于离子或角.如果您无法更改后端,则可以使用代理.
You cannot fix your issue by trying to enable CORS in your client. This is a general/ fundamental feature of http and not something specific to ionic or angular. If you have no way to change the back end then you can use a proxy.
"Ionic CLI引入了使代理服务器发出请求的功能,以解决您可能遇到的任何CORS问题.由于服务器向您的目的地发送了新的请求,因此将没有源,因此,没有需要CORS"
"The Ionic CLI introduced the ability to have a proxy server issue requests for you to get around any CORS issues you may have. Since the server is sending a fresh request to your destination, there will be no origin and therefore, no CORS needed"
as described here and example repo here
我想这是您如何在不启用后端的情况下尝试处理CORS请求的方法.
Which I assume is how you are trying to handle CORS request without enabling it in the back end.
请注意,当运行离子服务或离子运行-l时,当我们正在运行或测试我们的应用程序时,CORS只是一个问题."
Please note that "CORS is only an issue when we are running or testing our app when running ionic serve or ionic run -l."
设置代理:
- 在我们的ionic.project中设置代理
{
"name": "proxy-example",
"app_id": "",
"proxies": [
{
"path": "/api",
"proxyUrl": "http://cors.api.com/api"
}
]
}
- 将我们的端点URL替换为代理服务器
- 运行
离子服务
除此之外,解决CORS问题的最简单方法是最终要求您的API提供商允许所有主机"
Aside from this "The easiest way to handle the CORS problem is to ultimately ask your API provider to allow all hosts"
这篇关于在ionic-5角度被CORS政策阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!