Configuring a proxy server in Vite can be done by modifying the project's vite.config.js (or vite.config.ts) file. Vite provides built-in proxy support, commonly used to resolve cross-origin request issues during development.
javascript// vite.config.js or vite.config.ts import { defineConfig } from 'vite' export default defineConfig({ server: { proxy: { // String shorthand '/foo': 'http://localhost:4567', // Full configuration options '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, rewrite: (path) => path.replace(/^/api/, '') }, // Regular expression syntax '^/fallback/.*': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, rewrite: (path) => path.replace(/^/fallback/, '') } } } })
In this configuration, you can see several different proxy settings:
- String shorthand: All requests to
/fooare proxied tohttp://localhost:4567/foo. - Full configuration options: All requests to
/apiare proxied tohttp://jsonplaceholder.typicode.com, withchangeOrigin: trueindicating whether to modify theOriginheader. Therewriteoption is a function that modifies the proxied path; here it removes the/apiprefix. - Regular expression syntax: Matches all requests starting with
/fallback/and performs the corresponding proxying and rewriting.
It's important to note that when proxying requests, Vite preserves the original request path. If your proxy server requires a different path, you can rewrite it using the rewrite option.
After configuring, restart your Vite development server for the changes to take effect.
2024年6月29日 12:07 回复