为什么捐赠
API 浏览器
联系站长
Quasar CLI with Vite - @quasar/app-vite
开发时进行 API 代理

当开发时,我们常常需要访问后端提供的接口 API,我们可以让开发服务器将所有 API 请求代理到实际的后端。

例如,当您的 API 请求路径都是相对路径时,这就非常有用了,显然,这些相对路径的接口在开发环境下可能不存在。也就是说您可以使用代理 API 的方式创建与网站/应用部署时类似的环境。

为了配置代理规则,需要编辑 /quasar.config 文件中的 devServer.proxy 对象,在底层使用了 http-proxy 来实现代理,完整的配置项列表请参考

/quasar.config file

devServer: {
  proxy: {
    // 字符串简写:http://localhost:5173/foo -> http://localhost:4567/foo
    '/foo': 'http://localhost:4567',
    // 加上配置项:http://localhost:5173/api/bar-> http://jsonplaceholder.typicode.com/bar
    '/api': {
      target: 'http://jsonplaceholder.typicode.com',
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/api/, ''),
    },
    // 正则匹配:http://localhost:5173/fallback/ -> http://jsonplaceholder.typicode.com/
    '^/fallback/.*': {
      target: 'http://jsonplaceholder.typicode.com',
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/fallback/, ''),
    },
    // 使用代理实例
    '/api': {
      target: 'http://jsonplaceholder.typicode.com',
      changeOrigin: true,
      configure: (proxy, options) => {
        // proxy 对象是 'http-proxy' 的一个实例
      },
    },
    // 代理 WebSocket 或 socket.io:ws://localhost:5173/socket.io -> ws://localhost:5174/socket.io
    // 注意:使用 `rewriteWsOrigin` 时需谨慎,因为它可能会使代理暴露于 CSRF 攻击风险之下。
    '/socket.io': {
      target: 'ws://localhost:5174',
      ws: true,
      rewriteWsOrigin: true,
    },
  },
}