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

How to configure proxy in Vite?

1个答案

1

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

  1. Locate or create the Vite configuration file The root directory of a Vite project typically contains a file named vite.config.js or vite.config.ts.

  2. Configure the proxy Within this configuration file, modify the server.proxy option 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:

javascript
import { 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 /api to http://localhost:5000/api.
  • /api2: This detailed configuration sets changeOrigin to true to avoid host header issues, and uses the rewrite option 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.

2024年10月27日 17:32 回复

你的答案