網站首頁 編程語言 正文
1、例如:在api文件夾中新建一個api.js
// 公共的方法
const baseUrl = "http://192.xxx.xx.xx:8889"; // 請求地址
const $ajax = {
get: function({
url,
param,
header
}) {
return new Promise(function(resolve, reject) {
uni.request({
url: baseUrl + url,
data: param,
method: "GET",
success: function(res) {
if (res.statusCode !== 200) {
reject(res);
} else {
resolve(res);
}
},
fail: function(err) {
reject(err);
}
})
})
},
post: function({
url,
data,
header
}) {
return new Promise(function(resolve, reject) {
uni.request({
url: baseUrl + url,
data: data,
method: "POST",
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: function(res) {
if (res.statusCode !== 200) {
reject(res)
} else {
resolve(res);
}
},
fail: function(err) {
reject(err)
}
})
})
},
postJSON: function({
url,
data,
header
}) {
return new Promise(function(resolve, reject) {
uni.request({
url: baseUrl + url,
data: data,
method: "POST",
header: {
'Content-Type': 'application/json;charset=UTF-8'
},
success: function(res) {
if (res.statusCode !== 200) {
reject(res)
} else {
resolve(res);
}
},
fail: function(err) {
reject(err)
}
})
})
},
upImg: function({
url,
imgUrl
}) {
return new Promise(function(resolve, reject) {
uni.uploadFile({
url: "baseUrl" + url,
filePath: imgUrl,
name: 'file',
success: function(uploadFileRes) {
resolve(uploadFileRes);
},
fail: function(err) {
reject(err)
}
});
})
}
}
export default $ajax;
2、引入
例如:在main.js中全局引入
// 在main.js中引入
import ajax from './api/api.js'
3、使用
// get請求
this.$ajax.get({
url: `/wx/wxLogin`,
param: {
password: this.pwd,
username: this.name,
uuid: this.uuid
}
}).then((res) => {
console.log(res.data)
})
4、攜帶token
有的接口在發送http請求的時候需要驗證token,登陸成功后我們需要把Authorization字段的值放到header里面,攜帶token去發送請求。
①在api文件夾中新建config.js文件,封裝一下方法
const app = {
apiUrl: 'http://192.xxx.xx.xxx:8889', //請求的地址
baseRequest(obj) {
try {
const userToken = uni.getStorageSync('userToken');
if (userToken) {
if (obj.header) {
obj.header["Authorization"] = userToken;
} else {
obj.header = {
"Authorization": userToken
};
}
obj.url = this.apiUrl + obj.url;
uni.request(obj)
} else {
console.log("獲取不到userToken")
}
} catch (e) {
console.log(e)
console.log("獲取不到userToken")
}
},
}
export default app
②登陸成功后設置緩存
// 設置緩存
uni.setStorageSync('userToken', res.data.token),
③其他地方調用
// 順便介紹一下獲取緩存
getToken() {
uni.getStorage({
key: 'userToken',
success: (res) => {
// console.log('這是獲取key中的內容',res)
this.tokenData = res.data;
console.log('這是獲取token', this.tokenData)
if (this.tokenData) {
}
}
})
},
// 注意要引入config.js
import app from "@../../api/config.js"
// 在methods中調用封裝好的方法
getMaintenance() {
app.baseRequest({
url: `/repairType/xxx/xxx`,
method: 'get',
success: (res) => {
}
})
},
5. 請求代碼優化(新增請求日志和響應日志)
①
// interface.js
const baseUrl = "https://xxxxxxxxxxx";
export default {
config: {
baseUrl: baseUrl,
header: {
'Content-Type':'application/json;charset=UTF-8',
'x-requested-with':"XMLHttpRequest"
},
data: {},
method: "GET"|| "POST",
dataType: "json", /* 如設為json,會對返回的數據做一次 JSON.parse */
responseType: "text",
success() {},
fail() {},
complete() {}
},
interceptor: {
request: null,
response: null
},
request(options) {
/* console.log('options11')
console.log(options) */
if (!options) {
options = {}
}
options.baseUrl = options.baseUrl || this.config.baseUrl
options.dataType = options.dataType || this.config.dataType
options.url = options.baseUrl + options.url
options.data = options.data || {}
options.method = options.method || this.config.method
if(options.header){
options.header['Content-Type'] = options.header['Content-Type']|| this.config.header['Content-Type']
}
return new Promise((resolve, reject) => {
let _config = null
options.complete = (response) => {
let statusCode = response.statusCode
response.config = _config
if (process.env.NODE_ENV === 'development') {
if (statusCode === 200) {
/* console.log("【" + _config.requestId + "】 結果:" + JSON.stringify(response.data)) */
}
}
if (this.interceptor.response) {
let newResponse = this.interceptor.response(response)
if (newResponse) {
response = newResponse
}
}
// 統一的響應日志記錄
_reslog(response)
if (statusCode === 200) { //成功
resolve(response);
} else {
reject(response)
}
}
_config = Object.assign({}, this.config, options)
_config.requestId = new Date().getTime()
if (this.interceptor.request) {
this.interceptor.request(_config)
}
// 統一的請求日志記錄
_reqlog(_config)
if (process.env.NODE_ENV === 'development') {
// console.log(_config)
// console.log("【" + _config.requestId + "】 地址:" + _config.url)
if (_config.data) {
// console.log("【" + _config.requestId + "】 參數:" + JSON.stringify(_config.data))
}
}
uni.request(_config);
});
},
get(url, data, options) {
if (!options) {
options = {}
}
options.url = url
options.data = data
options.method = 'GET'
return this.request(options)
},
post(url, data, options) {
if (!options) {
options = {}
}
options.url = url
options.data = data
options.method = 'POST'
return this.request(options)
},
put(url, data, options) {
if (!options) {
options = {}
}
options.url = url
options.data = data
options.method = 'PUT'
return this.request(options)
},
delete(url, data, options) {
if (!options) {
options = {}
}
options.url = url
options.data = data
options.method = 'DELETE'
return this.request(options)
}
}
/**
* 請求接口日志記錄
*/
function _reqlog(req) {
if (process.env.NODE_ENV === 'development') {
console.log("【" + req.requestId + "】 地址:" + req.url)
if (req.data) {
console.log("【" + req.requestId + "】 請求參數:" + JSON.stringify(req.data))
}
}
}
/**
* 響應接口日志記錄
*/
function _reslog(res) {
let _statusCode = res.statusCode;
if (process.env.NODE_ENV === 'development') {
console.log("【" + res.config.requestId + "】 地址:" + res.config.url)
if (res.config.data) {
console.log("【" + res.config.requestId + "】 請求參數:" + JSON.stringify(res.config.data))
}
console.log("【" + res.config.requestId + "】 響應結果:" + JSON.stringify(res))
}
switch(_statusCode){
case 200:
break;
case 401:
break;
case 404:
break;
default:
break;
}
}
②
// index.js
import http from './interface'
export const execute = (data = {}) => {
if (data.url != 'logon') {
//設置請求前攔截器
http.interceptor.request = (config) => {
let token = uni.getStorageSync('accessToken')
delete config.header['Authorization']
if (token) {
config.header['Authorization'] = token
}
}
//設置請求結束后攔截器
http.interceptor.response = async (response) => {
const statusCode = response.statusCode;
if (response.header.authorization) {
uni.setStorageSync('accessToken', response.header.authorization)
}
if (statusCode === 401) {
uni.showToast({
title: '登錄已失效,請重新登錄',
icon: 'none',
duration: 2000
})
setTimeout(() => {
uni.navigateTo({
url: "../../pages/login/login"
});
uni.removeStorageSync('accessToken');
}, 2000)
}
return response;
}
return http.request(data)
} else {
return http.request(data)
}
}
const interfaces = {
}
export default {
execute,interfaces
}
?
原文鏈接:https://blog.csdn.net/qq_42540989/article/details/105096360
相關推薦
- 2023-07-29 git如何配置多個SSH
- 2022-07-11 SOC驗證環境的啟動方式
- 2022-08-25 Python進階Matplotlib庫圖繪制_python
- 2022-05-25 使用Python繪制三種概率曲線詳解_python
- 2022-04-09 C#8.0中的索引與范圍功能介紹_C#教程
- 2023-04-04 Swift中的HTTP請求體Request?Bodies使用示例詳解_IOS
- 2024-03-28 mac vscode 命令行啟動命令安裝 別名設置方法
- 2022-10-19 python類參數定義及數據擴展方式unsqueeze/expand_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支