1.taro 初始化项目时选择 taro-ui 库 ,在使用时任然需要 npm install taro-ui
2.taro 封装拦截器 三个文件
httpService.js 文件内容 ======
import Taro from '@tarojs/taro';
import apiConfig from './apiConfig'
//网络请求拦截器
const interceptor = function (chain) {
const requestParams = chain.requestParams
const { method, data, url } = requestParams
let token = Taro.getStorageSync('TOKEN')//拿到本地缓存中存的token
requestParams.header = {
...requestParams.header,
Authorization: 'Bearer ' + token //将token添加到头部
}
return chain.proceed(requestParams).then(res => { return res })
}
Taro.addInterceptor(interceptor)
const request = async (method, url, params) => {
//由于post请求时习惯性query参数使用params,body参数使用data,而taro只有data参数,使用contentType作为区分,因此此处需要做一个判断
let accessToken = ''
try {
var value = Taro.getStorageSync('userInfo')
if (value) {
accessToken = value?.accessToken;
}
} catch (e) {
// Do something when catch errorlll
}
let contentType = params?.data ? 'application/json' : 'application/x-www-form-urlencoded';
if (params) contentType = params?.headers?.contentType || contentType;
const option = {
method,
isShowLoading: false,
url: apiConfig.baseUrl + url,
data: params,
header: {
'content-type': 'application/json',
"H-AUTH-TOKEN": accessToken ,//|| '16523120400030311701659288049'
"H-PLATFORM-INFO": "wechat"
},
success(res) {
//根据不同返回状态值3进行操作
switch (res?.statusCode) {
case 503: {
console.log(503);
}
console.log(res?.statusCode);
default:
break;
}
},
error(e) {
console.log('api', '请求接口出现问题', e);
}
}
const resp = await Taro.request(option);
return resp.data;//根据个人需要返回
}
export default {
get: (url, config) => {
return request('GET', url, config);
},
post: (url, config) => {
return request('POST', url, config);
},
put: (url, config) => {
return request('PUT', url, config);
},
delete: (url, config) => {
return request('DELETE', url, config);
},
patch: (url, config) => {
return request('PATCH', url, config);
},
}
apiConfig.js 文件内容
let baseUrlPrefix = ''
const env = process.env.NODE_ENV === 'development' ? 'development' : 'production'
console.log('编译环境:',process.env.NODE_ENV)
switch (env) {
case 'development':
// baseUrlPrefix = 'http://192.168.2.40:3000'
baseUrlPrefix = 'https://appdev.sg-chain.com'
break
case 'production':
baseUrlPrefix = 'https://app.sg-chain.com'
break
}
const api = {
baseUrl: baseUrlPrefix,
//其他相关变量
}
export default api
index.js api 接口统一接口
//可根据不同模块区分文件请求
import httpService from './httpService';
function login( params) {
return httpService.post(`/api/wechat/account/loginByMobile`,
params
)
}
export default {
logi
}