当前位置:网站首页>Enterprise level ~uni app network request encapsulation
Enterprise level ~uni app network request encapsulation
2022-06-24 23:36:00 【gblfy】
Directory structure ( The root directory starts )
├── api # All requests
│ └── user.js # User request api
├── store # overall situation store management
│ └── modules # api modular
│ │ └── user.js # User request module
│ └── index.js # State management initialization
├── utils # Global common method
│ ├── auth.js # Local cache
│ ├── env.js # Common parameters
│ └── request.js # Network request middleware
└── main.js # Entrance file Load components Initialization etc.
Here is the content of the document
api/user.js( User request api)
// Reference the network request middleware
import request from './../utils/request';
/**
* Login request
*/
export function login(data) {
return request({
url: '/user/login',
method: 'POST',
data
})
}
store/modules/user.js( User request module )
// Reference user request api
import {
login} from '../../api/user';
import {
setToken} from '../../utils/auth';
// Here are the parameters of the example wechat applet , You can modify the request parameters by yourself
const actions = {
login({
commit}, param) {
return new Promise((resolve, reject) => {
login({
iv: param.iv, // Request parameters ( You can modify )
code: param.code // Request parameters ( You can modify )
}).then(response => {
// You can add your own methods here
// Save the obtained token To the local and so on
// Must be in resolve Before execution
setToken(response.token) // Will get token Save to local
resolve(response)
}).catch(error => {
console.log(error)
})
})
}
};
export default {
namespaced: true,
actions
}
store/index.js( State management initialization configuration )
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( Local cache configuration )
const TokenKey = 'token';
// Authentication 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( Common parameters )
"use strict";
// Variables can be added and modified by themselves
export default {
// A container for storing variables
appid: '****',
baseUrl: 'http://**.***.***.***'
}
/**
* appid : Applet appid
* baseUrl : Server domain name
*/
utils/request.js( Network request middleware )
import {
getToken,removeToken} from '../utils/auth';
import env from '../utils/env';
function service(options = {
}) {
options.url = `${
env.baseUrl}${
options.url}`;
// Determine whether there is a local token, If it exists, take the request header
if (getToken()) {
options.header = {
'content-type': 'application/json',
'Authorization': `${
getToken()}` // Here is token( You can modify )
};
}
return new Promise((resolved, rejected) => {
options.success = (res) => {
// If the requested status code is not 200 Then do the following
if (res.data.code !== 200) {
// Unsuccessful status code pop-up
uni.showToast({
icon: 'none',
duration: 3000,
title: `${
res.data.msg}`
});
// Login failure
if (res.data.code === 403) {
// Clear the place token
removeToken()
// Close all pages and return to the login page
uni.reLaunch({
url: '/pages/login/login'
})
}
// Return error message
rejected(res)
} else {
// The requested status code is 200 Then return the content
resolved(res.data.data)
}
};
options.fail = (err) => {
// Request failed Popup
uni.showToast({
icon: 'none',
duration: 3000,
title: ' Server error , Please try again later '
});
rejected(err);
};
uni.request(options);
});
}
export default service;
边栏推荐
- Uninstall hero League
- Unveiling the secrets of the Winter Olympics | smartbi's partners supported the "front and back" of the Beijing Winter Olympics
- Classic interview questions and answers for embedded engineers
- Whereabouts computer desktop small arrow
- RT thread uses RT kprintf
- Simple use of libnum Library (hexadecimal string conversion)
- Volcano成Spark默认batch调度器
- Using ADC to control brushless motor source program STM32 library function
- Design and practice of vivo server monitoring architecture
- 去商场逛街
猜你喜欢

7-7 数字三角形

Go language pointer, value reference and pointer reference

Jetpack Compose 最新进展
![[introduction to UVM== > episode_8] ~ sequence and sequencer, sequence hierarchy](/img/d0/7d78b00e4f6ad1e8efb73a5d472b09.png)
[introduction to UVM== > episode_8] ~ sequence and sequencer, sequence hierarchy

QT cannot be edited with UTF-8

(Smooth)ScrollToPosition doesn't work properly with RecyclerView

22map introduction and API

SimpleDateFormat 格式化和解析日期的具体类

中学校园IP网络广播系统解决方案-校园数字IP广播系统方案设计指南

抖音实战~实现App端视频上传与发布
随机推荐
7-8 ladder cloud vertical
[JS] - [array application] - learning notes
普通人的生活准则
7-9 treasure hunt route
R语言使用glm函数构建泊松对数线性回归模型处理三维列联表数据构建饱和模型、使用summary函数获取模型汇总统计信息、解读模型系数交互作用及其显著性
Sword finger offer merges two sorted lists
No main manifest attribute in jar
22map introduction and API
7-7 digital triangle
基于三维GIS开发的水电工程建设方案
(Smooth)ScrollToPosition doesn't work properly with RecyclerView
How to resolve the 35 year old crisis? Sharing of 20 years' technical experience of chief architect of Huawei cloud database
What good smart home brands in China support homekit?
MySQL 表的增删查改
Record a Webflux application memory leak troubleshooting
R语言使用MASS包的polr函数构建有序多分类logistic回归模型、使用exp函数、confint函数、coef函数获取模型中每个变量(自变量改变一个单位)对应的优势比的置信区间
[JS] - [array, Stack, queue, Link List basis] - Notes
Collation of Digital IC design experience (II)
Andersen Global借助巴勒斯坦成员公司加强中东平台
Go language pointer, value reference and pointer reference