Home  >  Article  >  Web Front-end  >  How uniapp implements network request encapsulation

How uniapp implements network request encapsulation

coldplay.xixi
coldplay.xixiOriginal
2020-12-21 17:25:199693browse

Uniapp implements network request encapsulation method: first implement the initial request; then create a new [request.js] file, the code is [return new Promise((resolved, rejected) => {uni.request..] ;Finally just optimize.

How uniapp implements network request encapsulation

The operating environment of this tutorial: windows7 system, uni-app2.5.1 version, this method is suitable for all brands of computers.

Recommended (free): uni-app development tutorial

uniapp’s method of implementing network request encapsulation:

1. The initial request for uniapp is used as follows:

uni.request({
    url: 'https://www.example.com/request', //仅为示例,并非真实接口地址。
    data: {
        text: 'uni.request'
    },
    header: {
        'custom-header': 'hello' //自定义请求头信息
    },
    success: (res) => {
        console.log(res.data);
     }.fail = (err) => {
     console.log(err);
  }
});

2. We first perform a simple encapsulation through Promise and create a new request.js file:

//options参数我们后面会说
function service(options = {}) {
return new Promise((resolved, rejected) => {
uni.request({
   url: options.url, //仅为示例,并非真实接口地址。
   data: options.data,
   header: {
       'content-type': 'application/x-www-form-urlencoded',
       'accessToken': `${token}` //权限token 
   },
   success: (res) => {
      rejected(res.data);
   }.fail = (err) => {
   rejected(err)
 }
});
}
}
export default service;

3. Finally, we optimize again based on the previous step.

//把配置项单独处理
import store from '/store/index.js'; //vuex  
let server_url=' ';//请求地址
let token = ' ';  凭证
process.env.NODE_ENV === 'development' ? '192.168.0.1' : 'http://***/api' ; //环境配置
function service(options = {}) {
       store.state.token && (token = store.state.token); //从vuex中获取登录凭证
       options.url = `${server_url}${options.url}`;
          //配置请求头
        options.header = {
        'content-type': 'application/x-www-form-urlencoded',
        'accessToken': `${token}` //Bearer 
    };
    return new Promise((resolved, rejected) => {
                //成功
        options.success = (res) => {
              
            if (Number(res.data.code) == 0) {  //请求成功
                resolved(res.data.data);
            } else {
                uni.showToast({
                    icon: 'none',   
                    duration: 3000,
                    title: `${res.data.msg}`
                });
                rejected(res.data.msg);//错误
            }
        }
              //错误
        options.fail = (err) => {
            rejected(err); //错误
        }
        uni.request(options);
    });
}
export default service;

4. Now we use it in the page.

1. Create a new pages page.

The directory is as follows

┌─common

│ ├─request.js //Request

┌─ pages

│ ├─index

│ │ └─api.js //api list

│ │ └─index.vue //Page file

├─static

├─store

│ ├─index.js //vuex

├─main.js

├─App.vue

├─manifest.json

└─pages.json

2. Configure api list. api.js //api list

import request from '/common/request.js'
export function login(data) {
  return request({
    url: '/user/login',
    method: 'POST',
    data
  })
}

3. Use

import { login} from './api.js';  //引入需要的api
//发起请求
onLoad() {
login('parameter').then(data => {
   console.log(data);
});
}...
on the page

The above is the detailed content of How uniapp implements network request encapsulation. 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