我正在尝试通过 POST 从一个create-react-app应用程序调用一个Web服务,该应用程序运行在以Windows 10为操作系统的XAMPP(也尝试使用WAMP)上的本地虚拟主机。
http://test.local/
-在XAMPP虚拟主机上运行的本地服务器。http://localhost:3000
-创建反应应用网址axios.get
制成的axios.post
正确响应和test.local/
正确响应。axios.get
正确响应,而axios.post
不响应。由localhost:3000
axios.post
请求因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
})
我尝试了在配置对象中使用 和不 CORS设置的请求。
位于test.local/load/notifications/index.php
的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);
?>
我在php页面上的CORS标头设置为
header("Access-Control-Allow-Origin: *");
,所以我假设不是 除非我的语法关闭,否则与CORS相关。没有错误信息, 端点只是不返回响应。
httpd.conf
中的目录标志
<Directory />
AllowOverride none
Require local
Require ip 192.168.1.5
</Directory>
httpd-vhosts.conf
中的虚拟主机配置:
<VirtualHost *:80>
DocumentRoot "F:\test\public"
<Directory "F:\test\public">
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>
答案 0 :(得分:-1)
您是否故意使用<Directory />
?我不确定这是您的帖子中的错字,还是由于Directory节点的开始标记中的/
而使配置不正确。
我从未在有效的conf中看到它(虽然也许是有效的?),但是它立刻引起了我的注意,好像它是一个自动关闭的HTML标记。
答案 1 :(得分:-1)
经过进一步调查,这是邮寄请求中的有效载荷引起的CORS问题。我发现,如果我发出没有数据的发布请求,则它的工作原理与POST请求一样。通过将我的PHP文件更改为以下内容可以解决此问题:
<?php
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: *');
$mockDataFile = "./mockData.json";
$unencoded = json_decode(file_get_contents($mockDataFile));
echo json_encode($unencoded);
?>
丢失的那张是header('Access-Control-Allow-Headers: *');
。
这似乎不是CORS问题,因为从开发服务器发出请求时没有错误消息。我根本不认为要删除有效负载,只是偶然地我将其遗漏了,并且请求有效。
从另一个虚拟主机发出请求时,我看到了错误
Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
此新错误消息导致我在设置Access-Control-Allow-Headers时遇到this page。我建议您在设置此标志之前先阅读一下文章,因为*
允许任何您想做的事情。