Service called is unable to fetch data

Hi,

I am getting the below errors while making a service call in chrome and other browsers as well even though cors is enabled.

Origin http://localhost:8100 not found in Access-Control-Allow-Origin header.

XMLHttpRequest: Network Error 0x80070005, Access is denied.

XMLHttpRequest for https://cc.com/mobile/custom/PODetails/getToken required CORS preflight.

XMLHttpRequest for https://cc.com/mobile/custom/PODetails/getToken required Cross Origin Resource Sharing (CORS).

Any solutions.

Add the origin “http://localhost:8100” to the Access-Control-Allow-Origin header of the API you are using.

Alternatively, use a Service Proxy for development: GitHub - ionic-team/ionic-cli: The Ionic command-line interface

below is my code. i am using multiple service calls to fetch data from backend and then display the data on view. its not fetching data. i am calling the api on the ionViewDidLoad() finction of the page.

My code:

ionViewDidLoad() {
console.log(‘ionViewDidLoad PoCountPage’);
this.globals1.user_name;
let headers = new Headers;
headers.set(‘Content-Type’,‘application/json’);
headers.append(‘Authorization’,‘Basic QTQyMjY1OF9DT0VJTlNUQU5DRU1DUzFfTU9CSUxFX0FOT05ZTU9VU19BUFBJRDpYNGVzMS5mam5kZ2xwdw==’);
headers.append(‘Oracle-Mobile-Backend-Id’,‘de0f87ae-7dfc-4084-98e8-0234f8e771e4’);

let options = new RequestOptions({ headers: headers });
let body = { 'userName': this.globals1.user_name, 'password': this.globals1.pass_word }
let service = 'https://cc.com:443/mobile/custom/PODetails/getToken';
this.http
  .post(service, body, options)
  .map(res => res.json())
  .subscribe(
  data => {
    console.log(data);
    let userName = data.userName;
    let approverID = data.approverID;
    let approverName = data.approverName;
    let UserLanguagePreference = data.UserLanguagePreference;
    let Token = data.Token;

    window.localStorage.setItem("uName", userName);
    window.localStorage.setItem("token", Token);
    window.localStorage.setItem("approverName", approverName);
    window.localStorage.setItem("approverID", approverID);
    window.localStorage.setItem("UserLanguagePreference", UserLanguagePreference);

    let headers1 = new Headers;
       headers1.set('Content-Type', 'application/json');
       headers1.append('Authorization','Basic QTQyMjY1OF9DT0VJTlNUQU5DRU1DUzFfTU9CSUxFX0FOT05ZTU9VU19BUFBJRDpYNGVzMS5mam5kZ2xwdw==');
       headers1.append('Oracle-Mobile-Backend-Id','31e3aaea-cb0f-4b19-a089-b07031ca2f46');
    

    let options1 = new RequestOptions({ headers: headers1 });
    let body1 = {
      "soapenv:Body": {
        "parsererror": {
          "orac:getPurchaseOrderEmployeeProfile": {
            "userId": "jde"
          }
        }
      }
    };

    this.http
      .post('https://cc.com:443/mobile/custom/CatalentServiceAPI/getPurchaseOrderEmployeeProfile', body1, options1)
      .map(res => res.json())
      .subscribe(
      data => {
        this.globals1.approverId = data.Envelope.Body.getPurchaseOrderEmployeeProfileResponse.approverId;
        this.globals1.approverName = data.Envelope.Body.getPurchaseOrderEmployeeProfileResponse.approverName;

        let headers2 = new Headers;
         headers2.set('ontent-Type','application/json');
         headers2.append('Authorization','Basic QTQyMjY1OF9DT0VJTlNUQU5DRU1DUzFfTU9CSUxFX0FOT05ZTU9VU19BUFBJRDpYNGVzMS5mam5kZ2xwdw==');
         headers2.append('Oracle-Mobile-Backend-Id', '31e3aaea-cb0f-4b19-a089-b07031ca2f46');
        

        let options2 = new RequestOptions({ headers: headers1 });
        let body2 = {
          "getPurchaseOrdersCounts": {
            "approver": {
              "entityId": this.globals1.approverId
            }
          }
        };
        this.http
          .post('https://cc.com:443/mobile/custom/CatalentServiceAPI/getPurchaseOrdersCounts', body2, options2)
          .map(res => res.json())
          .subscribe(
          data => {
            let countPO = data.Body.getPurchaseOrdersCountsResponse.purchaseOrdersCountList;
            this.pocount = countPO;
          },
          (error) => {
            console.log('error, unable to fetch data');
            let alert = this.alertCtrl.create({
              title: 'Failed',
              subTitle: 'Unable to fetch data',
              buttons: ['ok']
            });
             alert.present();
          });
        },
        (error) => {
            console.log('error, unable to fetch data');
            let alert = this.alertCtrl.create({
              title: 'Failed',
              subTitle: 'Unable to fetch data',
              buttons: ['ok']
            });
             alert.present();
          }); 
       }, 
        (error) => {
            console.log('error, unable to fetch data');
            let alert = this.alertCtrl.create({
              title: 'Failed',
              subTitle: 'Unable to fetch data',
              buttons: ['ok']
            });
             alert.present();
           });                

}

even after adding the Access-Control-Allow-Origin header in my first http call,
i.e.
headers.append(‘Access-Control-Allow-Origin’,‘http://localhost:8100’);

i am getting the below error:

XMLHttpRequest cannot load https://cc.com/mobile/custom/PODetails/getToken. Response for preflight has invalid HTTP status code 407

The server has to respond with that header.
Check out the service proxies I linked to above, this might be the easier solution for you.

Also:
Please edit your post, it is not very readable at the moment.
Use the </> button above the input field to format your code, command line output or error message (select the text first, then click the button or wrap it in ``` manually). Check the preview if it looks better. This will make sure your text is readable and if it recognizes the programming language it also automatically adds code syntax highlighting. Thanks.

1 Like
ionViewDidLoad() {
 console.log(‘ionViewDidLoad PoCountPage’);
this.globals1.user_name;
 let headers = new Headers;
 headers.set(‘Content-Type’,‘application/json’);
headers.append(‘Authorization’,‘Basic QTQyMjY1OF9DT0VJTlNUQU5DRU1DUzFfTU9CSUxFX0FOT05ZTU9VU19BUFBJRDpYNGVzMS5mam5kZ2xwdw==’);
headers.append(‘Oracle-Mobile-Backend-Id’,‘de0f87ae-7dfc-4084-98e8-0234f8e771e4’);
let options = new RequestOptions({ headers: headers });
let body = { 'userName': this.globals1.user_name, 'password': this.globals1.pass_word }
let service = 'https://cc.com:443/mobile/custom/PODetails/getToken';
this.http
  .post(service, body, options)
  .map(res => res.json())
  .subscribe(
  data => {
    console.log(data);
    let userName = data.userName;
    let approverID = data.approverID;
    let approverName = data.approverName;
    let UserLanguagePreference = data.UserLanguagePreference;
    let Token = data.Token;

    window.localStorage.setItem("uName", userName);
    window.localStorage.setItem("token", Token);
    window.localStorage.setItem("approverName", approverName);
    window.localStorage.setItem("approverID", approverID);
    window.localStorage.setItem("UserLanguagePreference", UserLanguagePreference);

    let headers1 = new Headers;
       headers1.set('Content-Type', 'application/json');
       headers1.append('Authorization','Basic QTQyMjY1OF9DT0VJTlNUQU5DRU1DUzFfTU9CSUxFX0FOT05ZTU9VU19BUFBJRDpYNGVzMS5mam5kZ2xwdw==');
       headers1.append('Oracle-Mobile-Backend-Id','31e3aaea-cb0f-4b19-a089-b07031ca2f46');
    

    let options1 = new RequestOptions({ headers: headers1 });
    let body1 = {
      "soapenv:Body": {
        "parsererror": {
          "orac:getPurchaseOrderEmployeeProfile": {
            "userId": "jde"
          }
        }
      }
    };

    this.http
      .post('https://cc.com:443/mobile/custom/CatalentServiceAPI/getPurchaseOrderEmployeeProfile', body1, options1)
      .map(res => res.json())
      .subscribe(
      data => {
        this.globals1.approverId = data.Envelope.Body.getPurchaseOrderEmployeeProfileResponse.approverId;
        this.globals1.approverName = data.Envelope.Body.getPurchaseOrderEmployeeProfileResponse.approverName;

        let headers2 = new Headers;
         headers2.set('ontent-Type','application/json');
         headers2.append('Authorization','Basic QTQyMjY1OF9DT0VJTlNUQU5DRU1DUzFfTU9CSUxFX0FOT05ZTU9VU19BUFBJRDpYNGVzMS5mam5kZ2xwdw==');
         headers2.append('Oracle-Mobile-Backend-Id', '31e3aaea-cb0f-4b19-a089-b07031ca2f46');
        

        let options2 = new RequestOptions({ headers: headers1 });
        let body2 = {
          "getPurchaseOrdersCounts": {
            "approver": {
              "entityId": this.globals1.approverId
            }
          }
        };
        this.http
          .post('https://cc.com:443/mobile/custom/CatalentServiceAPI/getPurchaseOrdersCounts', body2, options2)
          .map(res => res.json())
          .subscribe(
          data => {
            let countPO = data.Body.getPurchaseOrdersCountsResponse.purchaseOrdersCountList;
            this.pocount = countPO;
          },
          (error) => {
            console.log('error, unable to fetch data');
            let alert = this.alertCtrl.create({
              title: 'Failed',
              subTitle: 'Unable to fetch data',
              buttons: ['ok']
            });
             alert.present();
          });
        },
        (error) => {
            console.log('error, unable to fetch data');
            let alert = this.alertCtrl.create({
              title: 'Failed',
              subTitle: 'Unable to fetch data',
              buttons: ['ok']
            });
             alert.present();
          }); 
       }, 
        (error) => {
            console.log('error, unable to fetch data');
            let alert = this.alertCtrl.create({
              title: 'Failed',
              subTitle: 'Unable to fetch data',
              buttons: ['ok']
            });
             alert.present();
           });

Regular readers of this column will know that I have a lot of heuristic rules. Obviously, you’re completely free to ignore any of them. Some that this code is breaking:

  • if the entirety of a function isn’t comfortably viewable without scrolling, it’s too big
  • if it’s obvious that you’re copypastaing stanzas, centralize them (such as the error handling)
  • if you have to have variable names xxx1 and xxx2, your function is doing too much
  • do your best to avoid ever referencing window in an Ionic app
  • give properties and variables descriptive names
  • let defaults do their work. in this case, this means letting Http deal with content type
  • have consistent and conventional naming. you are mixing case conventions all over the place. use camelCase for properties, variables, and methods, PascalCase for classes.
  • generally, do not mix map and subscribe. service providers should use map, pages should use subscribe. if you’re combining them, you aren’t separating functionality properly.
  • do not use any sort of storage (be it local, native, sqlite, ionic, or whatever) simply to pass information between objects. use shared providers for that. the only things you want to persist in storage are things that are supposed to survive app restarts.
  • centralize string constants like https://cc.com:443/mobile/custom/CatalentServiceAPI so that when they change, you only have to edit one place.
  • do not interact directly with Http in pages, only in service providers that provide Promises or Observables of business domain objects, not raw JSON
1 Like

What should be the proxyconfiguration in ionic.config.json if i am sending request through my localhost
http://localhost:8100 and the service url is ‘https://coeinstancemcs1-a422658.mobileenv.us2.oraclecloud.com:443/mobile/custom/PODetails/getToken’,

I tried to set my proxy settings in ionic.config.json as below:

“proxies”:[
{
“path”:“http://localhost:8100/”,
“proxyUrl”:“https://coeinstancemcs1-a422658.mobileenv.us2.oraclecloud.com:443/mobile/custom/PODetails/getToken
}
]

I can see the result in chrome when cors is enabled, but i am getting error in firefox and Internet Explorer.

What does that mean?

In “path” you have a path like “api” that you then use instead of your remote URL. In your example it would probably make sense to put “oracle” as the path" and proxyUrl “https://coeinstancemcs1-a422658.mobileenv.us2.oraclecloud.com:443/mobile/custom/”. Then in your code you call “oracle/PODetails/getToken” - the hostname is added automatically.

I was getting the below error in console in chrome:

XMLHttpRequest for https://coeinstancemcs1-a422658.mobileenv.us2.oraclecloud.com/mobile/custom/PODetails/getToken required Cross Origin Resource Sharing (CORS).
XMLHttpRequest for https://coeinstancemcs1-a422658.mobileenv.us2.oraclecloud.com/mobile/custom/PODetails/getToken required CORS preflight.

When i have installed Access-Control-Allow-Origin:* plugin in chrome, i get my data in console as below:

data {userName: "jde", approverID: "ID1", approverName: "nandini", UserLanguagePreference: "English", Token: "pwAAAAQDAgEBAAAAvAIAAAAAAAAsAAAABABTaGRyAk4Acwg4AC…FzCSfammLyk3vaWgZqOQg+p8NI7W6FwOdmNb0OdLDB6xOC+k="}

However, in firefox and IE I am still getting the below error:

XMLHttpRequest for https://coeinstancemcs1-a422658.mobileenv.us2.oraclecloud.com/mobile/custom/PODetails/getToken required Cross Origin Resource Sharing (CORS).
XMLHttpRequest for https://coeinstancemcs1-a422658.mobileenv.us2.oraclecloud.com/mobile/custom/PODetails/getToken required CORS preflight.

I will configure the proxy setting in ionic.config.json as you have mentioned here and see the results.