I am trying to perform a HTTP Post from my Angular 4 ASP.NET app to another domain I own with a PHP script. However, I am getting some console errors:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://{MYWEBSITE}/misc/jsondbinsert.php. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Error: Object { _body: error, status: 0, ok: false, statusText: "", headers: {…}, type: 3, url: null }
The PHP script in question is:
<?php
header('Access-Control-Allow-Origin: *'); // allow Cross-Origin-Resource-Sharing (CORS)
header('Access-Control-Allow-Methods: GET, POST');
$link = sqlsrv_connect("SQLSERVER",
array("Database"=>"DATABASE", "UID"=>"SoLegendary", "PWD"=>"PASSWORD"));
if (!$link)
{
die('Could not connect: ' . print_r(sqlsrv_errors()));
}
// retrieve data from post request (JSON form)
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$username = $request->username;
$message = $request->message;
// insert all data into table
$query = "INSERT INTO accounts (username, message)";
$query .= "VALUES ('{$username}', '{$message}')";
mysqli_query($link, $query);
echo "Thanks, {$username}, your message has been saved!<br><br>";
sqlsrv_close($link)
?>
And my angular function sending the request is:
url: string = 'http://MYWEBSITE/misc/jsondbinsert.php';
testbody: any = { "username": "johnsmith123", "message": "hello world!" };
httpPostTest()
{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(this.url, JSON.stringify(this.testbody), options)
.subscribe(
(data) =>
{
console.log('Got some data from backend: ', data);
},
(error) =>
{
console.log('Error: ', error);
})
}
Most other CORS questions and guides simply say to add the header(...) line to the top of the PHP script, but that hasn't changed anything for me.