How to use a different base URL
P粉805922437
P粉805922437 2024-01-16 23:30:16
0
1
417

During development, I used Vite for the React client for HMR on http://localhost:5173/ and used the Node backend to handle API calls and resources.

For production builds, Node will provide the frontend services, so I want to use /whatever/endpoint. So I need an overridden way to map / to http://my.api.host:3000/ when served by Vite.

I'm sure this must be a common operation, but I don't know how to do it. According to the documentation, I think this should be done:

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 trying to serve from http://localhost:5173.

P粉805922437
P粉805922437

reply all(1)
P粉556159786

To rewrite the API endpoints and serve resources from the correct location when using Vite for production, you can use the proxy option in the Vite configuration. Here's an example of how to configure it:

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/',
});

The 'rewrite' function is used to remove the /whatever/endpoint prefix from the request path before forwarding it to the target.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!