I have create my api/product-search.php backend in http://localhost/ like so:
<?php
header('Access-Control-Allow-Origin', '*');
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Request-Headers: *");
header("Access-Control-Request-Method", "GET, POST, PUT, DELETE, OPTIONS");
Header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
header('Content-type: application/json');
$myObj->name = "Test Product";
$myObj->qty = 30;
$myObj->sku = "test-p";
$myJSON = json_encode($myObj);
echo $myJSON; echo PHP_EOL;
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
?>
Using Angular HttpClient from http://localhost:4200/ like so:
getProducts(): Observable<any> {
return this.http.get(`http://localhost/api/product-search.php`, this.setHttpHeader());
}
private setHttpHeader() {
const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Access-Control-Request-Headers', '*')
.set('Access-Control-Request-Origin', '*');
const options = { headers: headers };
return options;
}
ngOnInit() {
this.getProducts().subscribe(
response => {
// alert('Response');
console.log(response);
},
error => {
// alert('Error');
console.log(error);
}
);
}
When I inspect the console I get the following error: Angular HttpClient Request
When I inspect the Network Tab I get 200 OK like so: Browser Network Tab
I can also curl successfully:
curl -i http://localhost/api/product-search.php
HTTP/1.1 200 OK
Date: Mon, 09 Dec 2019 15:16:37 GMT
Server: Apache/2.4.34 (Unix) PHP/7.1.23
X-Powered-By: PHP/7.1.23
Access-Control-Request-Headers: *
Access-Control-Allow-Origin: *
Content-Length: 100
Content-Type: application/json
{"name":"Test Product","qty":30,"sku":"test-p"}
Host: localhost
User-Agent: curl/7.54.0
Accept: */*
In Chrome: Google Chrome Browser
It Looks like the call is being made successfully in many ways far as The Network tab, Curl and browser can tell, as of Angular http.js not so it ain't happy and I am not sure why.
Thanks in advance!
This is because you've accidentally set the
Access-Control-Allow-Originrequest header asAccess-Control-Request-Origin, which is an invalid request header:Also, take note that you can't actually set request headers from the client - these should only be set on the server/backend.