Taro小程序开发
系列文章的所有文章的目录
【Taro开发】-初始化项目(一)
【Taro开发】-路由传参(二)
【Taro开发】-taro-ui(三)
【Taro开发】-带token网络请求封装(四)
前言
基于Taro的微信小程序开发,主要组件库为Taro-ui Taro-ui:基于 Taro 开发 UI 组件 一套组件可以在 微信小程序,支付宝小程序,百度小程序,H5 多端适配运行(ReactNative 端暂不支持) 提供友好的 API,可灵活的使用组件
提示:以下是本篇文章正文内容,下面案例可供参考
1.新建文件夹及文件
2.apiConfig
let baseUrlPrefix = ''
const env = process.env.NODE_ENV === 'development' ? 'development' : 'production'
console.log('编译环境:',process.env.NODE_ENV)
switch (env) {
case 'development':
baseUrlPrefix = 'http://...'
break
case 'production':
baseUrlPrefix = 'https://...'
break
}
const api = {
baseUrl: baseUrlPrefix,
}
export default api
3.httpService
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')
requestParams.header = {
...requestParams.header,
Authorization: 'Bearer ' + token
}
return chain.proceed(requestParams).then(res => { return res })
}
Taro.addInterceptor(interceptor)
const request = async (method, url, params) => {
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 && (params?.data || params?.params),
header: {
'content-type': contentType,
},
success(res) {
switch (res?.statusCode) {
case 503: {
...
break;
}
...
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);
},
}
4.使用
index.js
import httpService from './httpService';
function getUser(id, params) {
return httpService.get(`/user/${id}`, {
params
})
}
export default {
getUser
}
import service from "@/services";
service.getUser(1001,{...}).then(res=>console.log(res))
|