0

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.

  • Can you post the response from the options request, from the network tab in chrome's debugger? – David Mar 26 '18 at 07:12
  • https://i.imgur.com/c8Ki9xR.png tbh not too familiar with in-browser debugging but that's what im seeing after a post on the networks tab – SoLegendary Mar 26 '18 at 12:17
  • Click on `jsondbinsert.php` on the left column and post a new screenshot please (this will show headers) – David Mar 26 '18 at 12:53
  • https://i.imgur.com/qVk68TQ.png – SoLegendary Mar 28 '18 at 02:20
  • DId you see this thread https://stackoverflow.com/questions/18981339/http-options-request-on-azure-websites-fails-due-to-cors? – David Mar 28 '18 at 07:02

1 Answers1

0

Add header("Access-Control-Allow-Headers: X-Requested-With"); to your php script

Liju L
  • 114
  • 1
  • 4