“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
Uni-app is used to request network interfaces. You can send network requests through uni.requestt(OBJECT) and view official documents.
However, in the actual project development, the interface will increase because of the demand. If we request the interface every time, we will request the interface according to the request steps in the document, which will make the page code very complicated, and there will be a lot of redundant code. There are also several inconvenient problems:
- The request header is set separately for each network request
- Determining the correctness of the returned data involves repeating a lot of code each time
- Return data format changes where all network requests need to be modified
Therefore, we can wrap the network request “uni.request(OBJECT)” before connecting the interface to the project, and then import it in the global file (main.js). This will leave a lot of duplicate code and reduce the size of the project file.
So how do you encapsulate a request using UNI-app?
The specific steps are as follows:
Create request.js file in the root directory of the project to write encapsulated code.
1. Define the domain name: baseUrl; 2. Define method: API; 3. Make the asynchronous request through promise, and finally export the method.
const baseUrl = 'http://localhost:3000'
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
Copy the code
Second, in main.js global introduction, avoid every page or component needs to request interface, file repeated introduction, save code.
import request from './utils/request.js'
Vue.prototype.$request = request
Copy the code
Finally, use it in the component content that requires the request interface.
onLoad() {
this.loadList()
},
methods: {
loadList() {
this.$request('/posts').then(res => {
console.log(res)
})
}
}
Copy the code
In summary, the above package is just a package for Uni.reuqest, and there will be further optimization and integration of interfaces, interceptors, tokens and more. Please continue to pay attention!