当前位置:网站首页>企业级~uni-app网络请求封装
企业级~uni-app网络请求封装
2022-06-24 19:46:00 【gblfy】
目录结构(根目录开始)
├── api # 所有请求
│ └── user.js # 用户请求api
├── store # 全局store管理
│ └── modules # api模块
│ │ └── user.js # 用户请求模块
│ └── index.js # 状态管理初始化
├── utils # 全局公用方法
│ ├── auth.js # 本地缓存
│ ├── env.js # 公共参数
│ └── request.js # 网络请求中间件
└── main.js # 入口文件 加载组件 初始化等
下面是文档内容
api/user.js(用户请求api)
// 引用网络请求中间件
import request from './../utils/request';
/**
* 登陆请求
*/
export function login(data) {
return request({
url: '/user/login',
method: 'POST',
data
})
}
store/modules/user.js(用户请求模块)
// 引用用户请求api
import {
login} from '../../api/user';
import {
setToken} from '../../utils/auth';
//下面我是示例的微信小程序的参数,可自行修改请求参数
const actions = {
login({
commit}, param) {
return new Promise((resolve, reject) => {
login({
iv: param.iv, // 请求参数(可自行修改)
code: param.code // 请求参数(可自行修改)
}).then(response => {
// 这里可以自己添加方法
// 保存获取到的token到本地之类的
// 必须在resolve之前执行
setToken(response.token) //将获取到的token保存到本地
resolve(response)
}).catch(error => {
console.log(error)
})
})
}
};
export default {
namespaced: true,
actions
}
store/index.js(状态管理初始化配置)
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user
}
});
export default store
utils/auth.js(本地缓存配置)
const TokenKey = 'token';
// 认证令牌
export function getToken() {
return uni.getStorageSync(TokenKey)
}
export function setToken(token) {
return uni.setStorageSync(TokenKey, token)
}
export function removeToken() {
return uni.removeStorageSync(TokenKey)
}
utils/env.js(公共参数)
"use strict";
// 变量可自行添加修改
export default {
//存放变量的容器
appid: '****',
baseUrl: 'http://**.***.***.***'
}
/**
* appid : 小程序appid
* baseUrl : 服务端域名
*/
utils/request.js(网络请求中间件)
import {
getToken,removeToken} from '../utils/auth';
import env from '../utils/env';
function service(options = {
}) {
options.url = `${
env.baseUrl}${
options.url}`;
// 判断本地是否存在token,如果存在则带上请求头
if (getToken()) {
options.header = {
'content-type': 'application/json',
'Authorization': `${
getToken()}` // 这里是token(可自行修改)
};
}
return new Promise((resolved, rejected) => {
options.success = (res) => {
// 如果请求回来的状态码不是200则执行以下操作
if (res.data.code !== 200) {
// 非成功状态码弹窗
uni.showToast({
icon: 'none',
duration: 3000,
title: `${
res.data.msg}`
});
// 登陆失效
if (res.data.code === 403) {
// 清除本地token
removeToken()
// 关闭所有页面返回到登录页
uni.reLaunch({
url: '/pages/login/login'
})
}
// 返回错误信息
rejected(res)
} else {
// 请求回来的状态码为200则返回内容
resolved(res.data.data)
}
};
options.fail = (err) => {
// 请求失败弹窗
uni.showToast({
icon: 'none',
duration: 3000,
title: '服务器错误,请稍后再试'
});
rejected(err);
};
uni.request(options);
});
}
export default service;
边栏推荐
- 376. 機器任務
- Common regular expressions
- 7-6 铺设油井管道
- Ningde times will increase RMB 45billion: Hillhouse subscribes RMB 3billion and Zeng Yuqun still controls 23% of the equity
- Bubble sort
- Actipro WPF Controls 2022.1.2
- 372. chessboard coverage
- The dplyr package select function of R language moves the specified data column in the dataframe data to the first column (the first column) in the dataframe data column
- 六大行数据治理现状盘点:治理架构、数据标准与数据中台(2022.04)
- Actipro WPF Controls 2022.1.2
猜你喜欢

#22Map介绍与API

File contains vulnerability issues
![[introduction to UVM== > episode_8] ~ sequence and sequencer, sequence hierarchy](/img/d0/7d78b00e4f6ad1e8efb73a5d472b09.png)
[introduction to UVM== > episode_8] ~ sequence and sequencer, sequence hierarchy
![[basic knowledge] ~ half adder & full adder](/img/06/7f1ede65dca527c8630285b587a4ba.png)
[basic knowledge] ~ half adder & full adder

7-7 数字三角形
Record a Webflux application memory leak troubleshooting
![[JS] - [stack, team - application] - learning notes](/img/5b/b90ed8d3eb4fc0ab41c6ea8d092d0f.png)
[JS] - [stack, team - application] - learning notes

Actipro WPF Controls 2022.1.2

Actipro WPF Controls 2022.1.2

Morris traverse
随机推荐
7-2 solving the stock buying problem
[JS] - [tree] - learning notes
7-8 ladder cloud vertical
选择类排序法
7-7 求解众数问题
国内有哪些好的智能家居品牌支持homekit?
Morris traversal
What good smart home brands in China support homekit?
SimpleDateFormat 格式化和解析日期的具体类
Quickly build KVM virtual machine on # yyds dry goods inventory # physical machine
Laravel study notes
UNION ALL UNION FULL JOIN
R language uses the multinom function of NNET package to build an unordered multi classification logistic regression model, and uses exp function and coef function to obtain the corresponding odds rat
2021-2022 China's financial digitalization "new" insight Industry Research Report
7-3 最大子段和
Bubble sort
What you must know about time series database!
R language uses the aggregate function of epidisplay package to split numerical variables into different subsets based on factor variables, calculate the summary statistics of each subset, and customi
OpenSSL SSL_ read: Connection was reset, errno 10054
当初吃土建起来的“中台”,现在为啥不香了?