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

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


错误消息如下:


CORS 策略已阻止从源“http://localhost:8080”在“http://localhost/myapp/api/test/1”处对 XMLHttpRequest 的访问:对预检请求的响应未通过访问控制检查:请求的资源上不存在“访问控制-允许源”标头。


如您所见,这是CORS的问题。经过一些文档,这是我一直在做的修复它(仍然不起作用)。


公小号呼叫:


axios({

  method: 'get',

  url: 'http://localhost/myapp/api/test/1',

  data: JSON.stringify({}),

  headers: { 'Content-Type': 'application/json', },

  crossdomain: true,

});

如果我在我的网络浏览器中访问 http://localhost/myapp/api/test/1,我得到了我的回复。


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


header('Access-Control-Allow-Origin: *');

我配置了万向节:


已更改


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

激活了阿帕奇模块中的“headers_module”


重新启动所有内容,清除我的缓存,尝试从另一个浏览器...


仍然不起作用,我错过了什么吗?


Qyouu
浏览 109回答 2
2回答

侃侃尔雅

我在索引.php文件的顶部使用它来修复CORS问题:function cors() {&nbsp; &nbsp; // Allow from any origin&nbsp; &nbsp; if (isset($_SERVER['HTTP_ORIGIN'])) {&nbsp; &nbsp; &nbsp; &nbsp; header("Access-Control-Allow-Origin: *");&nbsp; &nbsp; &nbsp; &nbsp; header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");&nbsp; &nbsp; &nbsp; &nbsp; header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Type, Accept");&nbsp; &nbsp; &nbsp; &nbsp; header('Access-Control-Allow-Credentials: true');&nbsp; &nbsp; &nbsp; &nbsp; header('Access-Control-Max-Age: 86400');&nbsp; &nbsp; // cache for 1 day&nbsp; &nbsp; }&nbsp; &nbsp; // Access-Control headers are received during OPTIONS requests&nbsp; &nbsp; if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {&nbsp; &nbsp; &nbsp; &nbsp; if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // may also be using PUT, PATCH, HEAD etc&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");&nbsp; &nbsp; &nbsp; &nbsp; if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Type, Accept");&nbsp; &nbsp; &nbsp; &nbsp; exit(0);&nbsp; &nbsp; }}cors();

小怪兽爱吃肉

尝试将此扩展用于跨源。https://chrome.google.com/webstore/detail/moesif-orign-cors-changer/digfbfaphojjndkpccljibejjbppifbc
打开App,查看更多内容
随时随地看视频慕课网APP