uniapp vite 跨域配置如何实现

在uniapp中使用vite进行开发时,如何配置跨域请求?我在vite.config.js中尝试添加proxy配置,但请求仍然报跨域错误。具体应该怎样设置才能解决这个问题?需要修改哪些文件,配置哪些参数?

2 回复

vite.config.js 中配置 server.proxy

export default {
  server: {
    proxy: {
      '/api': {
        target: 'http://your-api.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
}

开发环境请求 /api/users 会被代理到 http://your-api.com/users


在 UniApp 中使用 Vite 进行跨域配置,可以通过修改 vite.config.js 文件中的 server.proxy 选项来实现。以下是具体步骤和示例代码:

步骤:

  1. 在项目根目录下找到或创建 vite.config.js 文件。
  2. 在配置对象中添加 server 字段,并设置 proxy 属性来定义代理规则。
  3. 重启开发服务器使配置生效。

示例代码:

// vite.config.js
import { defineConfig } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'

export default defineConfig({
  plugins: [uni()],
  server: {
    proxy: {
      // 代理以 '/api' 开头的请求
      '/api': {
        target: 'https://api.example.com', // 目标服务器地址
        changeOrigin: true, // 修改请求头中的 Origin 为目标地址
        rewrite: (path) => path.replace(/^\/api/, '') // 可选:重写路径,移除 '/api' 前缀
      }
    }
  }
})

说明:

  • target:指定代理的目标服务器地址。
  • changeOrigin:设置为 true 以修改请求头中的 Origin,避免某些服务器的 CORS 限制。
  • rewrite:可选函数,用于重写请求路径(例如移除前缀)。

使用方式:

在代码中发起请求时,使用 /api/xxx 路径,Vite 会自动代理到 https://api.example.com/xxx。例如:

uni.request({
  url: '/api/user', // 实际请求被代理到 https://api.example.com/user
  success: (res) => {
    console.log(res.data)
  }
})

注意事项:

  • 此配置仅在开发环境生效,生产环境需通过服务器端配置解决跨域问题。
  • 如果项目使用 HBuilderX,确保运行到浏览器时启用 Vite 模式。

通过以上配置,即可在 UniApp 开发环境中实现跨域代理。

回到顶部