1.taro 初始化項目時選擇 taro-ui 庫 ,在使用時任然需要 npm install taro-ui?
2.taro 封裝攔截器 三個文件
httpService.js 文件內(nèi)容 ======
import Taro from '@tarojs/taro';
import apiConfig from './apiConfig'
//網(wǎng)絡(luò)請求攔截器
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請求時習(xí)慣性query參數(shù)使用params,body參數(shù)使用data,而taro只有data參數(shù),使用contentType作為區(qū)分,因此此處需要做一個判斷
? 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) {
? ? ? //根據(jù)不同返回狀態(tài)值3進(jìn)行操作
? ? ? switch (res?.statusCode) {
? ? ? ? case 503: {
? ? ? ? ? console.log(503);
? ? ? ? }
? ? ? ? ? console.log(res?.statusCode);
? ? ? ? default:
? ? ? ? ? break;
? ? ? }
? ? },
? ? error(e) {
? ? ? console.log('api', '請求接口出現(xiàn)問題', e);
? ? }
? }
? const resp = await Taro.request(option);
? return resp.data;//根據(jù)個人需要返回
}
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 文件內(nèi)容
let baseUrlPrefix = ''
const env = process.env.NODE_ENV === 'development' ? 'development' : 'production'
console.log('編譯環(huán)境:',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,
//其他相關(guān)變量
}
export default api
index.js api 接口統(tǒng)一接口
//可根據(jù)不同模塊區(qū)分文件請求
import httpService from './httpService';
function login( params) {
? return httpService.post(`/api/wechat/account/loginByMobile`,
? ? params
? )
}
export default {
? ? logi
}