uniapp 跨域终极解决方案

3,702 阅读1分钟

常规方案

  1. manifest.json中设置
"h5": {
		"devServer": {
			"port": 8000, //端口号
			"disableHostCheck": true,
			"proxy": {
				"/api": {
					"target": "你的服务请求地址",
					"changeOrigin": true, //是否跨域
					"secure": false // 设置支持https协议的代理
				}
			}
		}
	}
  1. vue.config.js中设置

module.exports = {  
    /* 部署生产环境和开发环境下的URL:可对当前环境进行区分,baseUrl  Vue CLI 3.3 起已弃用,要使用publicPath */  
    publicPath: "",  
    assetsDir: "static/lipin",  
    outputDir: "dist",  
    runtimeCompiler: true,  
    productionSourceMap: false,  
    /* webpack-dev-server 相关配置 */  
    devServer: {  
        /* 自动打开浏览器 */  
        open: true,  
        /* 设置为0.0.0.0则所有的地址均能访问 */  
        host: devHost,  
        port: devPort,  
        https: false,  
        hotOnly: false,  
        /* 使用代理 */  
        proxy: {  
            '/': {  
                /* 目标代理服务器地址 */  
                target: proxy.target,  
                /* 允许跨域 */  
                changeOrigin: proxy.changeOrigin,  
            },  
        },  
    },  
}  

上述操作设置后均失败的同学们请看这里

uni.request({
			    url: '/web/getUserInfo', 
			    success: (res) => {
			        console.log(res.data);
			    }
			});
uni.request({
			    url: 'https://www.baodu.com/web/getUserInfo', 
			    success: (res) => {
			        console.log(res.data);
			    }
			});

总结:
接口封装时,url 不要把请求地址写入,这是关键点