Home>Article>Web Front-end> How uniapp encapsulates request requests
Uniapp encapsulates the request request method: first create a common folder under the project, and then create the [request.js] file; then open the [request.js] file and start writing the encapsulated code; finally make an asynchronous request through promise , and finally export the method.
The operating environment of this tutorial: windows7 system, uni-app2.5.1 version, thinkpad t480 computer.
Recommended (free):uni-app development tutorial
Uniapp encapsulates the request request method:
1. Create a new common folder under the project, and then create the request.js file
2. Open the request.js file and start writing the package The code
The idea is very simple
Define domain name: baseUrl;
Definition method: api;
Asynchronous request through promise, and finally export the method.
request.js reference code is as follows
const baseUrl = 'https://unidemo.dcloud.net.cn' const request = (url = '', date = {}, type = 'GET', header = { }) => { return new Promise((resolve, reject) => { uni.request({ method: type, url: baseUrl + url, data: date, header: header, dataType: 'json', }).then((response) => { setTimeout(function() { uni.hideLoading(); }, 200); let [error, res] = response; resolve(res.data); }).catch(error => { let [err, res] = error; reject(err) }) }); } export default request
3. Global registration in main.js
import request from 'common/request.js' Vue.prototype.$request = request
4. Page call
The index.vuethis.$request('/api/news', { // 传参参数名:参数值,如果没有,就不需要传 }).then(res => { // 打印调用成功回调 console.log(res) })
called by thepage is recommended for free learning:Programming Video
The above is the detailed content of How uniapp encapsulates request requests. For more information, please follow other related articles on the PHP Chinese website!