简体   繁体   中英

Ionic2,Angular2:How to avoid CORS issue while using http get for REST API service call?

I've my backend on some remote server for which I've the url. I need to render the data from there into my Ionic2,Angular2 project using HTTP GET and POST methods.But I'm thrown with this error when I'm trying to make a service call:

XMLHttpRequest cannot load http://192.162.91.159:8080/movieengine2/api/search/getMoviedetails . Response to preflight request doesn't pass access control check:No 'Access Control-Allow-Origin' header is present on the Requested resource.Origin ' http://localhost:8100 ' is therefore not allowed access/

I've searched quite a lot on the internet but most of those forums are too old. I've referred the following:

Angular 2 - No 'Access-Control-Allow-Origin' header is present on the requested resource

https://forum.ionicframework.com/t/cors-problem-with-ionic-2-and-angular-2-no-access-control-allow-origin-header-is-present-on-the-requested-resource/58350/6

https://forum.ionicframework.com/t/ionic-2-cors-issue/59815

https://github.com/angular/angular/issues/13554

This is what I've in my service file

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions, BaseRequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';

@Injectable()
export class TestService {
  backendUrl:string='';
  parameters: RequestOptions;

  constructor(public http: Http) {
    console.log('Hello TestService Provider');
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  private handleError(error: Response){
    return Observable.throw(error.json().error || 'Server Error')
  }


  get(url, params) 
  {
     var headers = new Headers
      ({
     'X-Requested-With': 'XMLHttpRequest'
      });
      headers.append("Accept", 'application/json');
     headers.append('Content-Type', 'application/json' );
      let options = new RequestOptions({ headers: headers });

        this.backendUrl='http://192.162.91.159:8080/movieengine2/api/search/'+url;
        return this.http.get(this.backendUrl).map(this.extractData).catch(this.handleError);
  }

I even tried adding this in my ionic.config.json

"proxies": [
{
    "path": "/api",
    "proxyUrl": "http://api.steampowered.com"
}

]

Can someone tell me how to avoid that issue ? I want a permanent solution which can work on either the device or the browser.Thanks in advance.These are the versions I'm using.

"cors": "^2.8.3",
"ionic-angular": "2.1.0",
"ionic-native": "2.4.1",
"ionicons": "3.0.0",
"rxjs": "5.0.0-beta.12",
"sw-toolbox": "3.4.0",
"underscore": "^1.8.3",
"zone.js": "0.6.26"

I'm unable to find a suitable solution for the version I'm using.

There are 4 ways of tackling this:

  1. You can set up a proxy ( read this tutorial )

  2. You can run your app through an emulator or a mobile phone (inconvinient)

  3. You can get past CORS issues by installing the cordova Whitelist plugin

  4. You can also try and install the Chrome Allow-Control-Origin extension .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM