英文:
How to use a different base url
问题
在开发过程中,我使用 Vite 在 http://localhost:5173/
上对 React 客户端进行 HMR,并为 API 调用和资源使用 Node 后端。
对于生产构建,Node 将提供前端服务,因此我希望在由 Vite 提供服务时使用 /whatever/endpoint
。因此,我需要一种在由 Vite 提供服务时重写这个路径的方法,以便将 /
映射到 http://my.api.host:3000/
。
我确信这一定是一个常见的操作,但我不知道如何做。从文档中,我认为这会起作用:
vite.config.js
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
提供服务。
英文:
During development, I have vite doing HMR for the React client on http://localhost:5173/
, and a Node backend for API calls and assets.
For the production build, Node will serve the frontend, so I want to use /whatever/endpoint
. So I need a way of rewriting this when being served by Vite, so that it maps /
to http://my.api.host:3000/
.
I'm sure this must be a common thing to do, but I can't see how to do it. From the docs I thought this would do it:
vite.config.js
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
})
but this:
backgroundImage: 'url(/img/backgrounds/main.jpg)'
Still tries to serve it from http://localhost:5173
答案1
得分: 1
要在生产环境中使用 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' 前缀。
英文:
To rewrite the API endpoint and serve the assets from the correct location when using Vite in production, you can use the proxy option in the Vite configuration. Here's an example of how you can configure it:
<br>
<br>
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/',
});
<br>
'rewrite' function is used to remove the /whatever/endpoint prefix from the request path before forwarding it to the target.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论