axios 从 Vue 应用程序到在 WAMP 上运行的 PHP API 的 CORS 问题

Cep*_*hou 1 php apache cors vue.js axios

我无法使用 axios 从 Vue 应用程序向 WAMP 上运行的 PHP API 发出 XHR 请求。

错误消息如下:

CORS 策略阻止了在 ' http://localhost/myapp/api/test/1 ' 从源 ' http://localhost:8080 '访问 XMLHttpRequest :对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”标头。

如您所见,这是 CORS 的问题。在一些文档之后,这是我一直在做的修复它(仍然无法正常工作)。

Axios 调用:

axios({
  method: 'get',
  url: 'http://localhost/myapp/api/test/1',
  data: JSON.stringify({}),
  headers: { 'Content-Type': 'application/json', },
  crossdomain: true,
});
Run Code Online (Sandbox Code Playgroud)

如果我在 Web 浏览器中访问http://localhost/myapp/api/test/1,我会收到回复。

我试图将这行代码放在我的 PHP API 中,在我的入口点 (index.php)

header('Access-Control-Allow-Origin: *');
Run Code Online (Sandbox Code Playgroud)

我配置了 WAMP :

更改了 httpd-vhosts.conf 和 httpd.conf

# Virtual Hosts

<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    Header set Access-Control-Allow-Origin "*"
    AllowOverride All
    Require local
  </Directory>
</VirtualHost>
Run Code Online (Sandbox Code Playgroud)
  • 激活 apache 模块中的“headers_module”

  • 重新启动一切,清除我的缓存,从另一个浏览器尝试......

仍然没有工作,我错过了什么吗?

小智 5

我在 index.php 文件的顶部使用它来修复 CORS 问题:

function cors() {
    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
        header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Type, Accept");

        exit(0);
    }
}
cors();
Run Code Online (Sandbox Code Playgroud)