阿里云主机折上折
  • 微信号
Current Site:Index > Configuration of proxy server

Configuration of proxy server

Author:Chuan Chen 阅读数:27622人阅读 分类: 构建工具

The Necessity of Proxy Server Configuration

The Vite development server can only handle local file requests by default. However, in actual development, it is often necessary to interact with backend APIs. Due to the browser's same-origin policy restrictions, directly requesting APIs from different origins will result in cross-origin issues. Configuring a proxy server can solve this problem by forwarding API requests to the target server, avoiding cross-origin errors.

Basic Proxy Configuration

In vite.config.js, configure the proxy using the server.proxy option. The simplest proxy configuration only requires the target address:

// vite.config.js
export default defineConfig({
  server: {
    proxy: {
      '/api': 'http://localhost:3000'
    }
  }
})

This configuration means that all requests starting with /api will be proxied to http://localhost:3000. For example, a frontend request to /api/users will be forwarded to http://localhost:3000/api/users.

Path Rewriting

Sometimes the backend API's path prefix differs from the frontend. The rewrite option can be used to modify the path:

// vite.config.js
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        rewrite: path => path.replace(/^\/api/, '')
      }
    }
  }
})

In this case, a request to /api/users will be forwarded to http://localhost:3000/users, removing the /api prefix.

Multi-Target Proxy Configuration

A project may need to connect to multiple backend services. Different targets can be configured for different paths:

// vite.config.js
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true
      },
      '/uploads': {
        target: 'http://localhost:4000',
        rewrite: path => path.replace(/^\/uploads/, '/static')
      }
    }
  }
})

Advanced Configuration Options

Proxy configurations support more advanced options:

// vite.config.js
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,  // Modifies the host in the request header to the target URL
        secure: false,      // May be needed when proxying to HTTPS
        ws: true,           // Proxies WebSocket
        headers: {
          'X-Custom-Header': 'value'
        },
        configure: (proxy, options) => {
          // Directly access the proxy instance for finer-grained control
        }
      }
    }
  }
})

Environment Variable Integration

In real-world projects, proxy target addresses may vary by environment. They can be configured using environment variables:

// vite.config.js
export default defineConfig(({ mode }) => ({
  server: {
    proxy: {
      '/api': {
        target: mode === 'development' 
          ? 'http://localhost:3000' 
          : 'https://api.example.com',
        changeOrigin: true
      }
    }
  }
}))

WebSocket Proxy

For applications requiring real-time communication, WebSocket also needs to be proxied:

// vite.config.js
export default defineConfig({
  server: {
    proxy: {
      '/socket': {
        target: 'ws://localhost:3001',
        ws: true,
        changeOrigin: true
      }
    }
  }
})

Custom Middleware

For more complex scenarios, you can directly manipulate the underlying connect instance:

// vite.config.js
export default defineConfig({
  server: {
    proxy: {
      // Basic proxy configuration
    },
    middlewareMode: true,
    configureServer(server) {
      server.middlewares.use('/custom', (req, res, next) => {
        // Custom handling logic
      })
    }
  }
})

Common Issue Resolution

If the proxy configuration is not working, check the following:

  1. Ensure the request path matches the proxy rules
  2. The configuration takes effect only after restarting the development server
  3. Complex URLs may need encoding
  4. Check Vite server logs to confirm if requests are being proxied correctly
// Example: Proxy with query parameters
export default defineConfig({
  server: {
    proxy: {
      '/search': {
        target: 'http://localhost:3000',
        rewrite: path => path + '&proxy=true'
      }
    }
  }
})

Performance Optimization Suggestions

For scenarios with a large number of API requests:

  1. Combine similar API paths under the same proxy rule
  2. Avoid overly broad path matching (e.g., / will proxy all requests)
  3. In production, APIs should be accessed directly to avoid unnecessary proxy layers
// Not recommended broad matching
export default defineConfig({
  server: {
    proxy: {
      '/': 'http://localhost:3000'  // Will proxy all requests, including static resources
    }
  }
})

Integration with Other Tools

When the project uses other tools, proxy configurations may need adjustments:

// Used with Vitest testing
export default defineConfig({
  test: {
    server: {
      proxy: {
        '/api': 'http://localhost:3000'
      }
    }
  }
})

Dynamic Proxy Configuration

For cases where the proxy target needs to be dynamically determined based on the request:

// vite.config.js
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        router: req => {
          // Return different targets based on request headers or other conditions
          return req.headers['x-api-version'] === 'v2' 
            ? 'http://localhost:3002' 
            : 'http://localhost:3001'
        }
      }
    }
  }
})

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.