uniapp跨域问题和接口封装
1.在manifest.json文件中配置跨域。3.在main.js种配置全局http。2.在封装接口中使用。
·
uniapp跨域问题
1.在manifest.json文件中配置跨域
"h5": {
"devServer": {
"https": false,
"proxy": {
"/api": {
"target": "http://192.168.0.17:9201/",//后端的服务器地址
"changeOrigin": true,
"ws": true,
"pathRewrite": {
"^/api": ""
}
}
}
}
}
2.在封装接口中使用
// //管理网络请求 (用着ifdef H5/#ifdef MP-WEIXIN ,用这两种判断是使用那种api,因为内置浏览器没有跨域问题,所以不用设置)
// #ifdef H5
var baseUrl='/api'
// #endif
// #ifdef MP-WEIXIN
var baseUrl = 'http://192.168.1.17:9202/';
// #endif
let http = (option) => {
return new Promise((resolve, reject) => {
uni.request({
url: baseUrl + option.url,
method: option.method || "get",
header: option.header || {
"third-session": uni.getStorageSync('userInfo').sessionKey
},
timeout: option.timeout || 6000,
data: option.data || {},
success: res => {
switch (res.data.code) {
case 200: // 请求正确
resolve(res)
console.log("12334",res)
break;
case 60001: // 登录超时
uni.showToast({
icon: 'none',
title: res.data.msg,
duration: 2000
})
uni.clearStorageSync()
resolve(res)
break;
default:
resolve(res)
break;
}
},
fail: err => {
uni.showToast({
title: "请求失败,请稍后再试",
icon: "none",
})
reject(err)
}
})
})
}
export default http;
3.在main.js种配置全局http
//接口全局使用
import http from '@/util/https.js'
Vue.prototype.$http = http
4.在方法种使用
miaosha() {
this.$http({
url: "navigation/appActivitylist",
}).then(res => {
// console.log("99998", res.data.data.name)
this.seckillList = res.data.data
// console.log("this.seckilList: ",this.seckilList);
})
},
更多推荐
已为社区贡献2条内容
所有评论(0)