The installation
NPM install qs // to serialize post dataCopy the code
The introduction of
import baseUrl from '.. /baseUrl'; Import qs from 'qs' // process dataCopy the code
Context switching

Uni-app uses process.env.node_env to determine whether the current environment is development or production. It is generally used to connect to the test server or production server for dynamic switching.

Uniapp has its own production and development environment and can be configured with other environments; You can check out the official documentation

Development environment and production environment

If (process.env.node_env === 'development'){console.log(' development')}else{console.log(' production ')}Copy the code
Setting of the POST request header

For post requests, you need to add some headers. The default header is: ‘Application/X-www-form-urlencoded’

header = {    'Content-Type': 'application/x-www-form-urlencoded',}
Copy the code
The response data

When the request parameter is returned; Look at the code data and give the response

Switch (dataType. Code * 1) {case 0: resolve(dataType) break; Case 1003: uni.showModal({title: 'Login expired ', Content:' Sorry login expired, please login again ', confirmText: 'Login again ', success: Function (res) {if (res.confirm) {// Click ok // go to console.log(' user '); Uni. NavigateTo ({// Remember that you need hapages.json to be consistent; Cannot have. Vue suffix URL: '/pages/views/login/index'}); } else if (res.cancel) {console.log(' user clicks cancel '); } } }) break; Case-1: uni.showModal({title: 'failed to request data ', Content:' Failed to get data! ', confirmText: 'confirm ', showCancel: false, success: Function (res) {if (res.confirm) {} else if (res.cancel) {console.log(' user clicks cancel '); } } }) break }Copy the code
The full version
import baseUrl from '.. /baseUrl'; Import qs from 'qs' // Process data const Request = (params) => {/* * 1 */ let _self = this; let url = params.url; let method = params.method || 'GET'; let data = params.data || {}; data.token = "default-access_token" // default-access_token /* *2. Check token */ if (! Params.token) {// If no token is passed let token = uni.getStoragesync ('token'); // Find if (! NavigateTo ({url: 'pages/views/login/index'}); } else { data.token = '179509245-9c91827e0224bdc18d0b118b8be1b5af'; }} /* * 3. Add header */ let defaultOpot = {// 'content-type ': 'application/x-www-form-urlencoded',' terminal-type ': 'innerH5', 'Content-Type': 'application/json; charset=UTF-8', If (method == 'POST') {header = {' content-type ': 'application/x-www-form-urlencoded', } data = qs.stringify(data) } // 5. Const requestUrl = baseurl.server + url; Uni. showLoading({title: 'loading... '}); Return new Promise((resolve, reject) => {uni. Request ({url: requestUrl, method: method, header: Object.assign({}, defaultOpot, header), data: data, dataType: 'json,}). Then (res = > {/ / success if (res [1] && res [1]. The statusCode = = = 200) {let {data: DataType} = res[1] switch (dataType. Code * 1) {case 0: resolve(dataType) break; Case 1003: uni.showModal({title: 'Login expired ', Content:' Sorry login expired, please login again ', confirmText: 'Login again ', success: Function (res) {if (res.confirm) {// Click ok // go to console.log(' user '); Uni. NavigateTo ({// Remember that you need hapages.json to be consistent; Cannot have. Vue suffix URL: '/pages/views/login/index'}); } else if (res.cancel) {console.log(' user clicks cancel '); } } }) break; Case-1: uni.showModal({title: 'failed to request data ', Content:' Failed to get data! ', confirmText: 'confirm ', showCancel: false, success: Function (res) {if (res.confirm) {} else if (res.cancel) {console.log(' user clicks cancel '); }}}) break}}).catch(err => {// error reject(err)}).finally(() => {console.log(' execute regardless of success ') uni.hideloading (); }) }) } export default requestCopy the code
Encapsulate an interface in an API
import request from '.. /.. */ export function getFloorList(){return request({url:'/***', method:'get' }) } export function getCartProducts(){ return request({ url:'/***', method:'POST' }) }Copy the code
Used in components
The introduction of
import {getFloorList,getCartProducts} from '.. /.. /api/mall/index.js';Copy the code
use
getFloorList().then(res=>{
	this.list = res.data
})
Copy the code

The above may not be complete; You can configure it according to your own needs