I’m attempting to call a webservice via POST from a create-react-app application to a local vhost running on XAMPP (also tried WAMP) with Windows 10 as the OS.
The local environments
http://test.local/
– Local server running on an XAMPP vhost.http://localhost:3000
– create react app url
What calls work in each circumstance
axios.get
responds correctly andaxios.post
responds correctly when made fromtest.local/
.axios.get
responds correctly andaxios.post
does not respond. when made from fromlocalhost:3000
The code used in my tests
axios.post
request that is failing from localhost:3000
axios.post('http://test.local/load/notifications/', { someData: 'someVal'},
{ headers: { "Access-Control-Allow-Origin": "*" }).then((resp) => {
console.log(resp.data); // no response in network tab of developer tools
}, (error) => {
// The request was made but no response was received
})
I’ve tried this request with and without the CORS setting in the configuration object.
PHP test file at test.local/load/notifications/index.php
<?php
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
$mockDataFile = "./mockData.json";
$unencoded = json_decode(file_get_contents($mockDataFile));
echo json_encode($unencoded);
?>
My CORS header on the php page is set to
header("Access-Control-Allow-Origin: *");
, so I’m assuming it’s not
CORS related unless my syntax is off. There is no error message, the
endpoint just doesn’t return a response.
Directory flag in httpd.conf
<Directory />
AllowOverride none
Require local
Require ip 192.168.1.5
</Directory>
vhost configuration in httpd-vhosts.conf
:
<VirtualHost *:80>
DocumentRoot "F:testpublic"
<Directory "F:testpublic">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
</Directory>
ServerName test.local
ServerAlias test.local
CustomLog "logs/test.local-access.log" common
ErrorLog "logs/test.local-error.log"
</VirtualHost>
2
Answers
After further investigation, it was a CORS issue caused by the payload in the post request. I found that if I made a post request with no data, it worked just like the POST request. This was fixed by changing my PHP file to the following:
The missing piece was
header('Access-Control-Allow-Headers: *');
.This is why the problem was hard to identify in my create-react-app
This new error message led me to this page on setting Access-Control-Allow-Headers . I recommend reading the article before setting this flag because
*
allows for anything, which you may not want.Are you using
<Directory />
on purpose? I’m not sure if that’s a typo in your post or if that could be something that’s throwing off your config because of the/
in the opening tag of the Directory node.I’ve never seen that in a valid conf (though maybe it’s valid?), but it immediately caught my eye almost as though it were a self-closing HTML tag.