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 changed the server configuration, changed the name ‘localhost’ to 127.0.0.1
(php -t 'myServerFolder' -S 127.0.0.1:1337
), this made 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
Using angular HttpClient
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');
...
I can access the server through the browser without problems. If any other information is needed, just ask . Code based on this example.