Google Cloud Shell环境下SvelteKit对接Laravel的CORS错误求助
在Google Cloud Shell中解决SvelteKit与Laravel后端的CORS问题
背景
- 开发环境:Google Cloud Shell(使用终端、云编辑器、Web预览功能),因公司政策限制无法在本地搭建开发环境,后续将部署至Google Cloud Run生产环境
- 技术栈:前端使用SvelteKit(首次接触),后端使用Laravel;本人具备丰富前端开发经验
问题重现
- 前端启动命令:
npm run dev -- --host或npm run preview -- --host,运行端口为5173 - 后端启动命令:
php artisan serve --host=0.0.0.0 --port=8000,通过该终端的Web预览功能获取Cloud Shell生成的域名(格式示例:https://8000-cs-<some ID number>-default.cs-europe-west1-onse.cloudshell.dev) - 前端发起AJAX请求代码:
const response = await fetch(`https://8000-cs-<some ID number>-default.cs-europe-west1-onse.cloudshell.dev/api/my_route_here`);
错误表现
- 请求返回302 Found状态码,触发CORS错误
- 开发者控制台报错:
Access to internal resource at 'https://accounts.google.com/o/oauth2/v2/auth?client_id=<some code>&redirect_uri=https%3A%2F%2Fssh.cloud.google.com%2Fdevshell%2Fgateway%2Foauth&response_type=code&scope=email&state=<some code>' (redirected from 'https://5173-cs-<some code>-default.cs-europe-west1-onse.cloudshell.dev/manifest.json') from origin 'https://5173-cs-<some code>-default.cs-europe-west1-onse.cloudshell.dev' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
已确认的配置与信息
- 后端URL验证:直接在浏览器粘贴后端Cloud Shell域名可正常显示Laravel默认页面
- Laravel的
config/cors.php配置:
<?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. | */ 'paths' => ['api/*', 'sanctum/csrf-cookie'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true, ];
请求解决方案
目前无法定位问题根源,恳请提供可行的CORS问题解决方法。
内容的提问来源于stack exchange,提问作者Alex Kerr
相关产品推荐
相关产品推荐

