search
HomeWeb Front-enduni-appHow uniapp implements network request encapsulation

How uniapp implements network request encapsulation

Dec 21, 2020 pm 05:25 PM
uniappRequest encapsulation

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.