1. First, create a new common folder under the root directory of the applet
2. Create a new baseurl.js file under the common folder, and use this file for the domain name
let baseUrl = ''; // domain name
export { baseUrl }
3. Create a new request.js file under the common folder to encapsulate the request interface for use
import { baseUrl } from './baseurl.js'
module.exports = { request : function(url, methodType, data){ let fullUrl = `${baseUrl}${url}` return new Promise((resolve,reject) =>{ uni.request({ url: fullUrl, method:methodType, data, header: { 'content-type': 'application/x-www-form-urlencoded', // default value "authorization": uni.getStorageSync ('token') // Check if the backend is needed, remove it if not }, success(res){ resolve(res); },
fail(res){
reject(res);
}
})
})
}
}
4. Create a new rapi.js file under the common folder and place all interfaces
import { request } from './request.js'
module.exports = { // Get interface data getlist: (data) => request('/api/goods/getlist', 'POST', data), }
5. After the above preparations are completed, it can be used next
How to use it on the page
const $api = require('../../common/api')
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
let data = {
keyword: this.title,
}
$api.getlist(data).then((res) => {
console.log(res,'res');
})
},
methods: {}
}
That's all
Notice:
Choose method 1 or method 2 according to personal habits
Method 1 article address: CSDN
Method 1 demo download address: Mini Program Interface Request Encapsulation API (1)-Javascript Documentation Resources-CSDN Download
Method 2 article address: https://mp.csdn.net/mp_blog/creation/editor/127677395
Method 2 demo download address: https://download.csdn.net/download/lovewangyage/86894139