UniApp跨域怎么解决?新手必看

248 阅读1分钟

什么是跨域?

在这里插入图片描述

不同协议,不同域名,不同端口,都会造成跨域。 简单来说,当你在前端页面请求一个不在同一个端口下的接口 比如你页面是 http://localhost:5173,但接口是 http://127.0.0.1:3000/list,这就属于跨域了。浏览器会拦截请求,出现各种错误。

注意:小程序、App 是没有跨域的

解决方案

vue3

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

// https://vitejs.dev/config/
export default defineConfig({
	plugins: [
		uni(),
	],
	server: {
		port: 5173,
		https: false,
		cors: true, // 允许跨域。解决前端调用其他域名接口的跨域问题![](media/17464165785066/Google%20Chrome%202025-05-05%2013.10.48.png)

		proxy: { // 代理配置,用于解决跨域问题,代理路径前缀。示例:前端请求 /dev-api/list 会被代理
			'/dev-api': { // 代理目标地址。示例:http://127.0.0.1:3000/dev-api/list 会被代理到 http://127.0.0.1:3000/list
				target: 'http://127.0.0.1:3000',
				changeOrigin: true, // 修改请求头中的 Origin。解决服务器对 Origin 的限制
				rewrite: (path) => path.replace(/^\/dev-api/, '') // 路径重写。示例:/dev-api/list -> /list
			},

		}
	}
})
// 使用示例:
// uni.request({
//   url: '/dev-api/list',
//   method: 'GET',
//   success: (res) => {
//     console.log('请求成功:', res.data)
//   }
// })
// 实际请求:http://127.0.0.1:3000/list

vue2

// vue.config.js
module.exports = {
  devServer: {
    port: 5173, // 开发环境端口号
    https: false, // 不启用 https
    proxy: {
      '/dev-api': {
        target: 'http://127.0.0.1:3000', // 目标接口地址
        changeOrigin: true, // 允许跨域
        pathRewrite: {
          '^/dev-api': '' // 重写路径
        }
      }
    }
  }
}

// 使用示例:
// uni.request({
//   url: '/dev-api/list',
//   method: 'GET',
//   success: (res) => {
//     console.log('请求成功:', res.data)
//   }
// })
// 实际请求:http://127.0.0.1:3000/list