Vite-Vue 应用 HTTP 请求重定向 - DEV 模式

问题描述 投票:0回答:1

我想在开发模式下(npm run dev)将HTTP请求的基本URL从Vite应用程序的主机地址(http://localhost:5173)更改为我的ASP .NET API的主机地址(http://localhost:5815) ).

但是在应用代理重定向请求后,我在运行 Vite-Vue 应用程序时遇到这样的错误:

我的 vite.config.js 文件:

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
  ],
  build: {
    cssCodeSplit: false,
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    proxy: {
      '/': {
        target: 'http://localhost:5815',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\//, '')
      }
    }
  }
})

我应该做什么才能重定向我的所有 HTTP 请求 在开发模式下运行我的 localhost:5173 到 localhost:5815 (npm run dev)?

我只提到仅使用 Vue 的类似项目,使用此 vue.config 文件:

const { defineConfig } = require('@vue/cli-service');

module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  devServer: {
    proxy: 'http://localhost:5815',
  },
});
vue.js vuejs3 vite
1个回答
1
投票

无论如何,你需要一个不同于根目录的路径(因为从根目录开始,加载网站的资源,如 CSS、JS 和其他文件)。

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:5815',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''), // It removes the /api from the request address, so it will truly be used only for differentiation
      },
    },
  },
})

/api
关联的每个地址都将被重定向到
localhost:5815
。在示例中,您会看到访问
localhost:5815/some-endpoint
:

// Before
axios.get('/some-endpoint') // With what you are currently trying, it will never work from the root
// Call http://localhost:5173/some-endpoint (Vite Host)

// After
axios.get('/api/some-endpoint') // With the /api proxy route defined now, it works
// Call http://localhost:5815/some-endpoint (Your Custom API)

在正式生产版本中如何修改这个目标代理地址?只需检查 Vite 当前是否运行在 dev 模式或 prod 模式即可。因此,可以动态设置地址。

const API_URI = process.env.NODE_ENV === 'production'
  ? 'http://example.com'    // in prod
  : 'http://localhost:5815' // in dev

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: API_URI,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
})
© www.soinside.com 2019 - 2024. All rights reserved.