参考文档
在 src/http
下创建 request.ts
, 写入如下配置:
import Taro from '@tarojs/taro'
import { encryptData } from './encrypt'console.log('NODE_ENV', process.env.NODE_ENV)
console.log('TARO_APP_PROXY', process.env.TARO_APP_PROXY)
const baseUrl = process.env.TARO_APP_PROXYinterface RequestParams {url: stringmethod: 'OPTIONS'|'GET'|'HEAD'|'POST'|'PUT'|'PATCH'|'DELETE'|'TRACE'|'CONNECT'data: anyheader?: anytimeout?: numberloadingTitle?: string[key: string]: any
}
export function request (params: RequestParams) {const { url, method, data, header, args: { timeout = 6000, loadingTitle = '' } } = paramsTaro.showLoading({title: loadingTitle,mask: true})return new Promise((resolve, reject)=>{Taro.request({data: encryptData(data, method),url: baseUrl + url,method: method,timeout: timeout,header: {'content-type': 'application/json;charset=UTF-8,text/plain,*/*',...header},success: (res) => { console.log('success', res)if (res.data.message.code === 0) {resolve(res.data.data)} else {console.log('message', res.data.message.message)showError(res.data.message.message)reject({ message: res.data.message.message })}},fail: (res) => {console.log('fail', res)showError('请求失败')reject({ fail: res })},complete: (res: any) => { console.log('complete', res)Taro.hideLoading()}}).catch(e => {console.log('catch err', e)showError(e.errMsg)})})
}
function showError (message: string) {Taro.showToast({title: message,icon: 'none', duration: 2000})
}
在 src/http
下创建 index.ts
并导出通用请求:
import { request } from '@/http/request'export function getAction (url: string, parameter: any, args = {}) {return request({url: url,method: 'GET',data: parameter,args: args})
}
export function postAction (url: string, parameter: any, args = {}) {return request({url: url,method: 'POST',data: parameter,args: args,header: {'Content-Type': 'application/x-www-form-urlencoded'}})
}
在页面内进行网络请求
<script setup lang="ts">
import { ref } from 'vue'
import Taro, { useLoad, usePullDownRefresh } from '@tarojs/taro'
import { getAction } from '@/http/index'const url = {detail: '/api/detail'
}
const detailData = ref()
useLoad(() => {getDetail()
})
usePullDownRefresh(async () => {await getDetail()Taro.stopPullDownRefresh()
})
function getDetail () {getAction(url.detail, { id: 1 }).then((res: any) => {console.log('detail', res)detailData.value = res.data}).catch((err) => {console.log('err', err)})
}
</script>