Laravel 9 + InertiaJS + Vite在Droplet上的CORS错误求助
问题背景
我在DigitalOcean Droplet上搭建了预发布环境,技术栈为Laravel 9 + InertiaJS,全程使用Vite构建。本地开发用Laravel Sail正常,但服务器直接部署后,访问时触发CORS错误,具体报错如下:
test-123:1 Access to script at 'http://[::1]:5173/@vite/client' from origin 'http://xxx' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space
local.
test-123:18 GET http://[::1]:5173/@vite/client net::ERR_FAILED
test-123:1 Access to script at 'http://[::1]:5173/resources/js/app.js' from origin 'http://xxx' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address spacelocal.
test-123:18 GET http://[::1]:5173/resources/js/app.js net::ERR_FAILED
test-123:1 Access to script at 'http://[::1]:5173/resources/js/Pages/GoalNotAvailable.vue' from origin 'http://xxx' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address spacelocal.
test-123:18 GET http://[::1]:5173/resources/js/Pages/GoalNotAvailable.vue net::ERR_FAILED
我保留了Laravel默认CORS设置,尝试过反向代理但无效,想知道如何在Droplet上运行应用的开发版本,以及为何现有设置无法解决问题。
解决步骤
1. 修改Vite配置绑定公网访问地址
Vite默认绑定localhost/[::1],外部环境请求私有回环地址会触发浏览器安全拦截。修改项目根目录的vite.config.js:
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import vue from '@vitejs/plugin-vue'; export default defineConfig({ plugins: [ laravel({ input: 'resources/js/app.js', refresh: true, }), vue({ template: { transformAssetUrls: { base: null, includeAbsolute: false, }, }, }), ], server: { host: '0.0.0.0', // 允许服务器所有网卡接收请求 port: 5173, cors: { origin: 'http://xxx', // 替换为你的Droplet公网域名/IP credentials: true }, hmr: { host: 'xxx', // 同样替换为Droplet公网域名/IP,禁止用localhost } } });
2. 调整Laravel环境变量
在.env文件中指定公网地址,确保资源路径正确:
APP_URL=http://xxx ASSET_URL=http://xxx:5173
3. 启动Vite开发服务器
启动时添加--host参数,强制Vite监听公网地址:
npm run dev -- --host
4. 开放服务器端口
在DigitalOcean控制面板的防火墙设置中,添加入站规则,允许TCP 5173端口的外部访问。
问题根源说明
- 浏览器的私有地址空间限制:非本地环境(
http://xxx)请求本地回环地址([::1]:5173)时,浏览器会触发安全拦截,这不属于常规CORS配置能解决的范畴,必须让Vite绑定公网地址而非本地回环。 - 反向代理无效大概率是因为代理目标仍指向
[::1]:5173,且未正确处理Vite热更新(HMR)的请求头。
内容的提问来源于stack exchange,提问作者Robert

