Vite Proxy配置詳解:從入門到實戰應用
一、什么是Proxy代理?
Proxy(代理)是開發中常用的解決跨域問題的方案。Vite內置了基于http-proxy
的代理功能,可以輕松配置API請求轉發。
二、基礎配置
在vite.config.js
中配置proxy選項:
export default defineConfig({server: {proxy: {/api: {target: http://localhost:3000,changeOrigin: true,rewrite: path => path.replace(/^\/api/, )}}}
})
target
: 代理目標地址changeOrigin
: 修改請求頭中的host為目標URLrewrite
: 路徑重寫
三、進階配置
1. 多代理配置
proxy: {/api1: {target: http://localhost:3001,// ...其他配置},/api2: {target: http://localhost:3002,// ...其他配置}
}
2. WebSocket代理
proxy: {/socket.io: {target: ws://localhost:3000,ws: true}
}
3. 自定義代理規則
proxy: {^/api/.*: {target: http://localhost:3000,bypass(req) {if (req.headers.accept.indexOf(html) !== -1) {return /index.html}}}
}
四、實戰應用
1. 解決開發環境跨域
proxy: {/api: {target: https://production-server.com,changeOrigin: true,secure: false}
}
2. 模擬不同環境API
const targetMap = {dev: http://dev-server,test: http://test-server,prod: https://prod-server
}proxy: {/api: {target: targetMap[process.env.NODE_ENV],changeOrigin: true}
}
五、常見問題
- 代理不生效:檢查路徑是否匹配,特別是正則表達式
- HTTPS證書問題:設置
secure: false
跳過證書驗證 - WebSocket無法連接:確保設置了
ws: true
六、總結
Vite的Proxy配置簡單強大,能有效解決開發中的跨域問題。通過靈活配置可以滿足各種復雜場景需求。
提示:生產環境應使用Nginx等服務器處理代理,Vite代理僅用于開發環境。