微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-离子无法打开cors

我正在尝试从Ionic Android应用程序中的实时服务器获取API数据,但它返回此错误

Access to XMLHttpRequest at 'https://example.com/api/categories/' from origin 'http://192.168.43.71:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

服务器设定

现在,我将Laravel用于实时服务器,它提供了API,这是我在laravel应用程序中设置CORS的方式:

/bootstrap/app.PHP

<?PHP
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET');
    header('Access-Control-Allow-Headers: *');
    // rest of the file

由于上面的设置,我在CORS测试仪上得到了这个结果

one

离子设置

因此,我一直在阅读如何解决此问题,并遇到了许多类似的解决方案,这就是我添加到ionic.config.json文件中的内容

"proxies": [
    {
      "path": "/api/*",
      "proxyUrl": "https://example.com/api/"
    }
  ]

获取请求(离子服务)

这是我请求我的get方法的方式

apiUrl = 'https://example.com/api/categories/';
  constructor(private http: HttpClient) { }

  getCategories(): Observable<any> {
    return this.http.get(`${this.apiUrl}`).pipe(
      map(categories => categories)
    );
  }

您知道该怎么做才能解决此问题?

解决方法:

我使用这些API标题解决了我的问题:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods:GET,POST");
header("Access-Control-Allow-Headers: Authorization, Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");

和Angular Http:

//GET data details
 getData(authToken){
      const httpOptions = {
          headers: new HttpHeaders({
              'Accept': 'application/json, text/plain',
              'Content-Type':  'application/json',
              'Authorization': authToken
            })
   };
   //console.log(authToken);
   return this.http.get(this.apiGetUrl, httpOptions).retry(3);
 }

 与上一个答案一样,“选项”请求会自动与GET或POST一起发送.如果您有apache服务器,则可以echo $headers = apache_request_headers();看看发生了什么.比较$_SERVER和Apache here.

就我而言,我运行if语句:

if(isset($headers["Authorization"]) && isset($headers["Content-Type"])){
  //handle get request
  }
else{
  //handle options request
   echo " False,Re-routing Options Request";
  }

我将在浏览器中测试您的HTTP调用,并查看开发工具以确认发送的请求.我希望这有帮助!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐