赞
踩
场景:需要一个H5页面去写支付界面,由于js太不好用了,所以利用uniapp搭建一个简单的平台。
ps:点击对应的uniapp项目框架时,需要注意自己本次开发所需要使用哪种语言(VUE2/VUE3)
在manifest.json —> 源码视图加入以下代码完成跨域
/* H5配置 */ "h5" : { "title" : "yubai", "devServer" : { // "https" : false, // 是否启用 https 协议,默认false "port" : 9999, "disableHostCheck" : true, "proxy" : { "/" : { "target": "http://172.XXX.1.220:8080/", // 目标地址 "changeOrigin" : false, //changeOrigin 这个配置项,修改的不是origin 头,而是 host 头,默认false "secure": true, // 是否支持https协议的代理 "pathRewrite" : { "^/" : "/" } } } } }
import configObj from '../config.js' //#ifdef H5 const BASE_URL = '' // #endif // #ifdef APP const BASE_URL = configObj.baseUrl // #endif const request = ({ url = '', method, header = {}, data = {}, showLoading =true })=>{ return new Promise((resolve,reject)=>{ uni.request({ url: BASE_URL +url,// 接口地址 链接+接口路径 method, header : { // 添加请求头 // "Authorization": "bearer " + uni.getStorageSync('Authorization').access_token, }, data,// 传递参数 success:(res)=>{ console.log(res) if(res.data.code === 200){ // 可以根据状态码进行对应的拦截 resolve(res.data) }else{ if(res.statusCode ==502||JSON.parse((res.data).msg == '')){ reject(JSON.parse(res.data)) }else{ reject(JSON.parse(res.data)) } } }, // 这里的接口请求,如果出现问题就输出接口请求失败的msg;对于请求失败的设置统一抛错提示了 fail: (err) => { uni.showToast({ title: "XXX" + err.msg, icon: 'none' }); reject(err) } }) }) } export default request
import request from './utils/request.js'
Vue.prototype.$request = request // vue文件调用时,指令 this.$request
调用接口请求注意,封装的返回值时promise数值,需要做对应的处理—async /await
method:{
async getAPI(){
try{
const res = await this.$request({
url :'/XXXX',
method:'get',
data:{ id:10086}
})
console.log(res)
}catch(e){
console.log(e)
}
}
}
创建package.json文件
{ "uni-app": { "scripts": { "build:test": { // 测试环境打包运行 "title": "build:test", "env": { "UNI_PLATFORM": "h5", "NODE_ENV": "development", "BASE_URL": "test", "DESCRIBE": "测试环境" } }, "build:pro": { "title": "build:pro",// 正式环境打包运行 "env": { "UNI_PLATFORM": "h5", "NODE_ENV": "production", "BASE_URL": "pro", "DESCRIBE": "正式环境" } } } } }
** process.env 是 Node.js 中的一个环境对象。其中保存着系统的环境的变量信息。
const node_dev = process.env.NODE_ENV
// 开发环境配置
let configObj = {
baseUrl:"/good"
}
if(node_dev){ // 如果存在则是打包上线状态,否则 就是本地环境运行
// 打包环境配置
configObj = {
baseUrl:process.env.BASE_URL
}
}
export default configObj
import configObj from './config.js'
Vue.prototype.$configObj = configObj
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。