微信小程序封装
import __config from '后端地址'
const request = (url, method, data, showLoading) => {
let _url = __config.basePath + url
return new Promise((resolve, reject) => {
if (showLoading) {
wx.showLoading({
title: '加载中',
})
}
wx.request({
url: _url,
method: method,
data: data,
header: {
'app-id': wx.getAccountInfoSync().miniProgram.appId,
'third-session': getApp().globalData.thirdSession != null ? getApp().globalData.thirdSession : ''
},
success(res) {
if (res.statusCode == 200) {
if (res.data.code != 200) {
console.log(res.data)
wx.showModal({
title: '提示',
content: res.data.msg ? res.data.msg : '没有数据' + '',
success() {
},
complete() {
if (res.data.code == 60001) {
//session过期,则清除过期session,并重新加载当前页
getApp().globalData.thirdSession = null
wx.reLaunch({
url: getApp().getCurrentPageUrlWithArgs()
})
}
}
})
reject(res.data.msg)
}
resolve(res.data)
} else if (res.statusCode == 404) {
wx.showModal({
title: '提示',
content: '接口请求出错,请检查手机网络',
success(res) {
}
})
reject()
} else {
console.log(res)
wx.showModal({
title: '提示',
content: res.errMsg + ':' + res.data.message + ':' + res.data.msg,
success(res) {
}
})
reject()
}
},
fail(error) {
console.log(error)
wx.showModal({
title: '提示',
content: '接口请求出错:' + error.errMsg,
success(res) {
}
})
reject(error)
},
complete(res) {
wx.hideLoading()
}
})
})
}
module.exports = {
request,
login: (data) => { //小程序登录接口
//data:要传输的数据,false取消提示,true信息提示
return request('/weixin/api/ma/wxuser/login', 'post', data, false)
},
wxUserGet: (data) => { //微信用户查询
return request('/weixin/api/ma/wxuser', 'get', null, false)
}
}
app.js注册
import api from './utils/api'
页面调用接口
//注册APP.js内容
const app = getApp()
//post 传输数据
app.api.userAddressSave({
id: this.data.userAddress.id,
userName: value.userName,
telNum: value.telNum,
provinceName: region[0],
cityName: region[1],
countyName: region[2],
detailInfo: value.detailInfo,
isDefault: this.data.userAddress.isDefault
}) .then(res => {//回调函数
wx.navigateBack()
})
},
//get传递数据
app.api.userAddressPage(this.data.page)
.then(res => {
let userAddress = res.data.records
this.setData({
userAddress: userAddress,
loadmore: false
})
})
vue接口数据封装
//调用utils统一封装数据接口
import request from '@/utils/request'
export function getPage(query) {
return request({
url: '/goodscategory/page',
method: 'get',
params: query
})
}
export function addObj(obj) {
return request({
url: '/goodscategory',
method: 'post',
data: obj
})
}
export function delObj(id) {
return request({
url: '/goodscategory/' + id,
method: 'delete'
})
export function putObj(obj) {
return request({
url: '/goodscategory',
method: 'put',
data: obj
})
}
requst数据接口封装
import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
// axios中请求配置有baseURL选项,表示请求URL公共部分
baseURL: process.env.VUE_APP_BASE_API,
// 超时
timeout: 10000
})
// request拦截器
service.interceptors.request.use(config => {
// 是否需要设置 token
const isToken = (config.headers || {}).isToken === false
if (getToken() && !isToken) {
config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
}
// get请求映射params参数
if (config.method === 'get' && config.params) {
let url = config.url + '?';
for (const propName of Object.keys(config.params)) {
const value = config.params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof(value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
let params = propName + '[' + key + ']';
var subPart = encodeURIComponent(params) + "=";
url += subPart + encodeURIComponent(value[key]) + "&";
}
} else {
url += part + encodeURIComponent(value) + "&";
}
}
}
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(res => {
// 未设置状态码则默认成功状态
const code = res.data.code || 200;
// 获取错误信息
const msg = errorCode[code] || res.data.msg || errorCode['default']
if (code === 401) {
MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
location.href = '/index';
})
})
} else if (code === 500) {
Message({
message: msg,
type: 'error'
})
return Promise.reject(new Error(msg))
} else if (code !== 200) {
Notification.error({
title: msg
})
return Promise.reject('error')
} else {
return res.data
}
},
error => {
console.log('err' + error)
let { message } = error;
if (message == "Network Error") {
message = "后端接口连接异常";
}
else if (message.includes("timeout")) {
message = "系统接口请求超时";
}
else if (message.includes("Request failed with status code")) {
message = "系统接口" + message.substr(message.length - 3) + "异常";
}
Message({
message: message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
vue封装接口调用
//注册post.js文件的方法
import {addObj} from "@/api/system/post";
getList() {
//调用方法
addObj(this.queryParams).then(response => {
this.postList = response.rows;
this.total = response.total;
this.loading = false;
});
},
vue数据保存到cookie
//保存数据cookie域,cookie存在该名称就无法保存
Cookie.set(name,data);
//删除cookie
Cookie.remove(name);
//获取cookie数据
cookies.get('name');
vue localStorage 数据保存到本地
localStorage解决了cookie存储空间不足的问题(cookie中每条cookie的存储空间为4k),localStorage中一般浏览器支持的是5M大小,这个在不同的浏览器中localStorage会有所不同。
localStorage的使用
localStorage.getItem(key):获取指定key本地存储的值
localStorage.setItem(key,value):将value存储到key字段
localStorage.removeItem(name);//删除本地数据