乐闻世界logo
搜索文章和话题

How to configure vite.config to proxy a server at a different port

1个答案

1

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:

  1. String shorthand: All requests to /foo are proxied to http://localhost:4567/foo.
  2. Full configuration options: All requests to /api are proxied to http://jsonplaceholder.typicode.com, with changeOrigin: true indicating whether to modify the Origin header. The rewrite option is a function that modifies the proxied path; here it removes the /api prefix.
  3. 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 回复

你的答案