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 Promise
s or Observable
s 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.