如何配置 apache VHost 以与 axios.post 一起工作?

How to configure apache VHost to work with axios.post?

我正在尝试通过 POST 从 create-react-app 应用程序调用网络服务到本地虚拟主机 运行 XAMPP (也尝试过 WAMP), Windows 10 作为 OS.


本地环境


在每种情况下什么叫有效


我测试中使用的代码

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
})

I've tried this request with and without the CORS setting in the configuration object.


PHP 测试文件位于 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.


httpd.conf

中的目录标志
<Directory />
    AllowOverride none
    Require local
    Require ip 192.168.1.5
</Directory>

httpd-vhosts.conf 中的 vhost 配置:

<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>

您是故意使用 <Directory /> 吗?我不确定这是否是您的 post 中的拼写错误,或者是否由于目录节点的开始标记中的 / 而导致您的配置丢失。

我从未在有效的 conf 中看到它(虽然它可能有效?),但它立即引起了我的注意,几乎就像它是一个自动关闭的 HTML 标签。

经过进一步调查,这是由 post 请求中的负载引起的 CORS 问题。我发现如果我发出一个没有数据的 post 请求,它就像 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: *');


这就是为什么在我的 create-react-app 中很难发现问题的原因

This didn't appear to be a CORS issue because there was no error message when making the request from the dev server. I simply didn't think to remove the payload, it was only by accident that I left it out and the request worked.

When making the request from another vhost, I saw the error Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.


这个新的错误消息让我 this page 设置 Access-Control-Allow-Headers 。我建议在设置此标志之前阅读这篇文章,因为 * 允许任何你可能不想要的东西