Ionic can't get open cors

后端 未结 3 1743
慢半拍i
慢半拍i 2021-01-17 03:34

I am trying to get API data from live server in ionic android app but it returns this error:

Access to XMLHttpRequest at \'https://example.com/api/categories         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-17 04:26

    I solved my issue using these Headers for my 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");

    And 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);
     }
    Like the previous answer, an Options request automatically gets sent with the GET or POST. If you have apache servers, you can echo$headers = apache_request_headers(); to see what is all coming through. Comparison for $_SERVER and Apache here.

    In my case, I run if statements:

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

    I would test your HTTP call in the browser and look at dev tools to confirm the requests being sent. I hope this helps!

提交回复
热议问题