Post, PostData, CORS

I don't know the problem I have, it's one or the other.


I'm using TWebHttpRequest to access some web services written in PHP.

using httpGET, its fine.

using httpPOST is not - nothing gets through. So this is either that I'm not using the PostData property properly, or because I've not to CORS headers right in the PHP.  It works fine using a browser and PostMan.

So, CORS. I've used a number of alternative commands, all of which their authors swear work perfectly. They seem to come down to this:
        header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Credentials: true');
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
        header("Access-Control-Allow-Headers: *");

Using TWebHttpRequest:
     WebHttpRequest1.OnResponse := MyRequest1Response;
     WebHttpRequest1.Command    := httpPost;
     WebHttpRequest1.PostData := 'room=101';
     WebHttpRequest1.URL := 'https://test.net/test.php';
     WebHttpRequest1.execute;

test.php simply executes 

print_r of the $_POST array;

I get nothing.  Just an empty array.

Can anyone tell me what I'm doing wrong?






When you open the browser console, do you see any kind of error?

It works fine using a browser and using Postman. 


I also use the same apis from mobile (Firemonkey) apps, so I'm doubly perplexed.

Just to add, this is testing from localhost, if that makes any difference. 

Again, do you see an error in the browser console?

In the browser (Edge):


 SEC7120: [CORS] The origin 'http://localhost:8000' did not find 'http://localhost:8000' in the Access-Control-Allow-Origin response header for cross-origin  resource at 'http://iotops.net/test3.php'.



Please enable CORS on the PHP request


See: https://stackoverflow.com/questions/8719276/cors-with-php-headers

OK, got it. 


FYI
The problem was that the default value of 'Headers' in the TWebHTTPRequest is:

Cache-Control=no-cache, no-store, must-revalidate


and in the PHP header in my test webservice, I had:


header("Access-Control-Allow-Headers: X-Requested-With");


The error complained that 'Cache-Control' was not allowed in the Access-Control-Allow-Headers.


So, 2 days later, I added 'Cache-Control' to the PHP header list (case-sensitive) and it worked.


I'm not really confident I know why it worked, i.e. wouldn't have ben particularly surprised if it hadn't.



Anyway, hope it helps.





For PHP, you indeed need to add this Access-Control header.
From the TWebHttpRequest, we add by default the cache control to avoid possible cached responses that could lead to incorrect (old) information. If your server has a problem with this, removing it is a solution.