跨域常见错误
Access to XMLHttpRequest at 'http://example.com/api' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
我们在开发网站时,特别是前后端分离的网站,前端和后端不是同一个域名会出现这样的错误。
解决方案
我前面提过一个开源项目(thinkphp8+vue3开源项目,部署就能直接使用,论文查重+AIGC检测)就是前后端分离的,我们看看这个项目是怎么解决这个问题的。
首先我们看到 composer.json 中有 topthink/think-cors 说明这个项目用了 topthink/think-cors。我们搜索 topthink/think-cors 就可以找到详细的说明。
安装:
bash
composer require topthink/think-cors
配置文件 config/cors.php :
php
<?php
return [
'paths' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_methods' => ['*'],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 7200,
'supports_credentials' => true,
];
这样跨域错误就应该解决了。