Home>Article>Web Front-end> How uniapp encapsulates request requests

How uniapp encapsulates request requests

coldplay.xixi
coldplay.xixi Original
2020-12-09 15:38:28 6788browse

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.

How uniapp encapsulates request requests

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

How uniapp encapsulates request requests

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

How uniapp encapsulates request requests

4. Page call

The index.vue

this.$request('/api/news', { // 传参参数名:参数值,如果没有,就不需要传 }).then(res => { // 打印调用成功回调 console.log(res) })

called by the
  

page 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn