Configuring proxy in Vite primarily addresses cross-origin request issues in the development environment. Vite utilizes a robust development server that supports forwarding specific API requests to another server via proxy configuration, thereby bypassing browser same-origin policy restrictions.
Implementation Steps
-
Locate or create the Vite configuration file The root directory of a Vite project typically contains a file named
vite.config.jsorvite.config.ts. -
Configure the proxy Within this configuration file, modify the
server.proxyoption to set up the proxy. This option accepts an object where the keys represent the request paths to proxy (which can be specific API paths or matching patterns), and the values are objects specifying the target and other configurations.
Example Code
Assume you have an API service running at http://localhost:5000, while your Vite service runs at http://localhost:3000. You want to proxy all requests to /api to http://localhost:5000. You can configure your vite.config.js as follows:
javascriptimport { defineConfig } from 'vite'; export default defineConfig({ server: { proxy: { // Using string shorthand '/api': 'http://localhost:5000', // Full format '/api2': { target: 'http://localhost:5000', changeOrigin: true, rewrite: (path) => path.replace(/^/api2/, '') } } } });
Configuration Explanation
/api: This shorthand method forwards all requests to/apitohttp://localhost:5000/api./api2: This detailed configuration setschangeOrigintotrueto avoid host header issues, and uses therewriteoption to modify URL paths.
How to Test if the Configuration is Effective?
Start your Vite development server locally and attempt to request the proxied API. If configured correctly, you should observe requests being properly forwarded and receiving responses from the target server.
Notes
- Ensure the target server for the proxy is running correctly.
- After modifying the configuration file, it is typically necessary to restart the Vite development server.
By doing this, you can efficiently handle cross-origin request issues in your local development environment, enhancing the development experience.