在开发过程中,我使用Vite为React客户端在http://localhost:5173/上进行HMR,并使用Node后端处理API调用和资源。
对于生产构建,Node将提供前端服务,所以我想使用/whatever/endpoint。因此,当由Vite提供服务时,我需要一种重写的方式,将/映射到http://my.api.host:3000/。
我确定这一定是一个常见的操作,但我不知道如何做到。根据文档,我认为应该这样做:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
export default defineConfig({
plugins: [react()],
server: {
origin: 'http://my.api.host:3000'
},
base: 'http://my.api.host:3000'
})
但是这个:
backgroundImage: 'url(/img/backgrounds/main.jpg)'
仍然尝试从http://localhost:5173提供服务。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
要在使用Vite进行生产时,重写API端点并从正确位置提供资源,您可以在Vite配置中使用代理选项。以下是如何配置的示例:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react-swc'; export default defineConfig({ plugins: [react()], server: { proxy: { '/whatever/endpoint': { target: 'http://my.api.host:3000', changeOrigin: true, rewrite: (path) => path.replace(/^\/whatever\/endpoint/, ''), }, }, }, base: 'http://my.api.host:3000/', });'rewrite'函数用于在将请求路径转发到目标之前,从请求路径中删除/whatever/endpoint前缀。