I am getting this error in Angular when I make a call to the PHP server. This is the error:
Access to XMLHttpRequest at 'https://p/angular/php/login.php' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
In the php I only have a echo "1";
and the instructionheader('Access-Control-Allow-Origin: *');
import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-api-login',
templateUrl: './api-login.component.html',
styleUrls: ['../app.component.css']
})
export class ApiLoginComponent implements OnInit {
usuario: String="";
clave: String="";
url: string;
display: String;
constructor(public router: Router, private http: HttpClient){
this.url="https://pr.es/angular/php/login.php"
this.display="block";
}
ngOnInit() {}
closeModal(){
this.display='none';
}
login(usuario, clave){ //Metodo
this.usuario=usuario.value;
this.clave=clave.value;
const req = this.http.post(this.url,{
usuario: 'PrecaNuevo',
clave: 'PrecaNuevo'
})
.subscribe(
res => {
console.log(res);
},
err => {
console.log("Error occured");
}
);
}
}
I have tried to configure a proxy according to what I have read in some manual In my package.json I have among other things
"start": "ng serve --proxy-config proxy.config.json",
And my proxy.config.json file which is in the same directory.
{
"/angular/php/*":{
"target": "https://pr.es/",
"secure": false,
"logLevel":"debug"
}
}
The CORS protocol makes the browser complete a request first
OPTIONS
, before doing aGET
or aPOST
, you have to return the header there.You should also add another header,
Access-Control-Allow-Methods
with a value similar toGET, POST, PUT, DELETE, OPTIONS, HEAD
.Another option is to configure a reverse proxy, you can see it in this other answer to a similar problem
And, in addition, you can find more information about CORS in this very complete answer
Try something like this and see if it fixes it for you:
a chrome extension cors extension can also serve Make sure to activate it. I clarify that it is not the best way to solve it, but it can help