React+Laravel部署Plesk后仍遇CORS错误,请求排查
排查Laravel + React部署在Plesk上的CORS跨域问题
前端基于React JS开发,后端采用Laravel框架,二者均部署在Plesk平台。已在Laravel后端配置CORS,但仍出现跨域错误,前后端均为HTTPS环境。
Laravel后端cors.php配置
return [ /* |-------------------------------------------------------------------------- | Cross-Origin Resource Sharing (CORS) Configuration |-------------------------------------------------------------------------- | | Here you may configure your settings for cross-origin resource sharing | or "CORS". This determines what cross-origin operations may execute | in web browsers. You are free to adjust these settings as needed. | | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS | */ 'paths' => ['*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['url_of_react_app'], 'allowed_origins_patterns' => ['*'], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ];
错误信息
Access to XMLHttpRequest at 'URL_of_laravel_backend' from origin
'URL_of_React_app' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
React应用API配置代码
import axios from "axios"; export const baseURL = "URL_of _laravel_backend"; export const axiosPublicInstance = axios.create({ baseURL, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, });
排查步骤
- 确认Laravel的CORS中间件已注册:检查
app/Http/Kernel.php的api中间件组中是否包含\Fruitcake\Cors\HandleCors::class,若需全局生效,可将其加入全局中间件列表。 - 校验
allowed_origins的URL格式:确保填写完整的HTTPS地址(如https://your-react-domain.com),无拼写错误或多余斜杠。 - 清除Laravel配置缓存:执行
php artisan config:clear和php artisan cache:clear命令,避免部署后旧配置被缓存。 - 移除前端请求中的
Access-Control-Allow-Origin头:该头由后端返回给浏览器,前端请求添加此头无效,需从axios配置中删除。 - 检查Plesk服务器配置:确认Plesk的Nginx/Apache配置未覆盖Laravel的CORS响应头,比如是否在.htaccess或Nginx额外配置中添加了冲突的CORS规则。
- 测试OPTIONS预请求:使用curl命令测试预请求是否正常返回CORS头,示例:
查看返回的响应头中是否包含curl -X OPTIONS -H "Origin: https://your-react-app.com" https://your-laravel-backend.com/api/your-endpointAccess-Control-Allow-Origin。
内容的提问来源于stack exchange,提问作者Guest2096
相关产品推荐
相关产品推荐

