API 浏览器
Quasar CLI with Vite - @quasar/app-vite
面向开发者的 API 代理

将项目文件夹(由 Quasar CLI 创建)与现有后端集成时,一个常见的需求是使用开发服务器访问后端 API。为了实现这一点,我们可以并行(或远程)运行开发服务器和 API 后端,并让开发服务器将所有 API 请求代理到实际的后端。

¥When integrating a project folder (created by Quasar CLI) with an existing backend, a common need is to access the backend API when using the dev server. To achieve this, we can run the dev server and the API backend side-by-side (or remotely), and let the dev server proxy all API requests to the actual backend.

如果你在 API 请求中访问相对路径,这将非常有用。显然,这些相对路径在你开发过程中可能无法使用。为了创建类似于你已部署的网站/应用所使用的环境,你可以代理 API 请求。

¥This is useful if you access relative paths in your API requests. Obviously, these relative paths will probably not work while you are developing. In order to create an environment similar to the one used by your deployed website/app, you can proxy your API requests.

要配置代理规则,请在 devServer.proxy 中编辑 /quasar.config 文件。在底层,它使用 http-proxy。其 此处 选项的完整列表。

¥To configure the proxy rules, edit the /quasar.config file in devServer.proxy. Under the hood, it uses http-proxy. Full list of its options here.

/quasar.config file

devServer: {
  proxy: {
    // string shorthand: http://localhost:5173/foo -> http://localhost:4567/foo
    '/foo': 'http://localhost:4567',
    // with options: http://localhost:5173/api/bar-> http://jsonplaceholder.typicode.com/bar
    '/api': {
      target: 'http://jsonplaceholder.typicode.com',
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/api/, ''),
    },
    // with RegExp: http://localhost:5173/fallback/ -> http://jsonplaceholder.typicode.com/
    '^/fallback/.*': {
      target: 'http://jsonplaceholder.typicode.com',
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/fallback/, ''),
    },
    // Using the proxy instance
    '/api': {
      target: 'http://jsonplaceholder.typicode.com',
      changeOrigin: true,
      configure: (proxy, options) => {
        // proxy will be an instance of 'http-proxy'
      },
    },
    // Proxying websockets or socket.io: ws://localhost:5173/socket.io -> ws://localhost:5174/socket.io
    // Exercise caution using `rewriteWsOrigin` as it can leave the proxying open to CSRF attacks.
    '/socket.io': {
      target: 'ws://localhost:5174',
      ws: true,
      rewriteWsOrigin: true,
    },
  },
}