I’m a couple of days trying to debug some app with HTTP requests in a localhost server. I think this is the one of the most frustrating errors that I stumbled across. The first error was with CORS, followed by some others, something like this:
XMLHttpRequest cannot load http://localhost:8888.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8100' is therefore not allowed access.
I tried to allow all domains in the server configuration and in the app options, nothing changed. Later I did so many things that I don’t even remember what I did to stop that CORS error, but I don’t effectively fixed it, the other errors keeping haunting me:
I also tried to deactive the chrome CORS with an extension and later with the options: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
. Nothing changed.
Ionic v4
Dev Server: PHP built in server
Running with: ionic serve
home.page.ts
...
async Save(data) {
let myLink = "http://localhost:1337/upload.php"
let myDataArray = [{"point_id" : this.point_id, "name" : this.name, "obs" : this.obs, "coord" : this.coord}];
let myData = JSON.stringify(myDataArray);
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Accept': 'application/json'
})
};
const loading = await this.loadingController.create({
message: 'Uploading data...',
});
await loading.present();
this.http.post(myLink, myData, httpOptions)
.pipe(
finalize(() => {
loading.dismiss();
})
)
.subscribe(res => {
if (res['success']) {
this.presentToast('Data upload complete.')
} else {
this.presentToast('Data upload failed.')
}
});
}
upload.php (headers only)
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header('Content-Type: application/json');
...
If any other information is needed, just ask