search
HomeWeb Front-enduni-appHow uniapp implements network request encapsulation
How uniapp implements network request encapsulationDec 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
如何在uniapp中实现图片预览功能如何在uniapp中实现图片预览功能Jul 04, 2023 am 10:36 AM

如何在uni-app中实现图片预览功能引言:在移动应用开发中,图片预览是一项常用的功能。在uni-app中,我们可以通过使用uni-ui插件或自定义组件来实现图片预览功能。本文将介绍如何在uni-app中实现图片预览功能,并附带代码示例。一、使用uni-ui插件实现图片预览功能uni-ui是由DCloud开发的一套基于Vue.js的组件库,提供了丰富的UI组

如何在uniapp中实现相机拍照功能如何在uniapp中实现相机拍照功能Jul 04, 2023 am 09:40 AM

如何在uniapp中实现相机拍照功能现在的手机功能越来越强大,几乎每个手机都配备了高像素的相机。在UniApp中实现相机拍照功能,可以为你的应用程序增添更多的交互性和丰富性。本文将针对UniApp,介绍如何使用uni-app插件来实现相机拍照功能,并提供代码示例供参考。一、安装uni-app插件首先,我们需要安装一个uni-app的插件,该插件可以方便地在u

手把手教你uniapp和小程序分包(图文)手把手教你uniapp和小程序分包(图文)Jul 22, 2022 pm 04:55 PM

本篇文章给大家带来了关于uniapp跨域的相关知识,其中介绍了uniapp和小程序分包的相关问题,每个使用分包小程序必定含有一个主包。所谓的主包,即放置默认启动页面/TabBar 页面,以及一些所有分包都需用到公共资源/JS 脚本;而分包则是根据开发者的配置进行划分,希望对大家有帮助。

uniapp中如何使用地理位置获取功能uniapp中如何使用地理位置获取功能Jul 04, 2023 am 08:58 AM

uniapp是一种基于Vue.js的跨平台开发框架,它可以同时开发微信小程序、App和H5页面。在uniapp中,我们可以通过使用uni-api来访问设备的各种功能,包括地理位置获取功能。本文将介绍在uniapp中如何使用地理位置获取功能,并附上代码示例。首先,在uniapp中使用地理位置获取功能,我们需要在manifest.json文件中申请权限。在man

uniapp中如何使用视频播放器组件uniapp中如何使用视频播放器组件Jul 04, 2023 am 10:13 AM

uniapp中如何使用视频播放器组件随着移动互联网的发展,视频已成为人们日常生活中不可或缺的娱乐方式之一。在uniapp中,我们可以通过使用视频播放器组件来实现视频的播放和控制。本文将介绍如何在uniapp中使用视频播放器组件,并提供相应的代码示例。一、引入视频播放器组件在uniapp中,我们需要先引入视频播放器组件才能使用它的功能。可以通过在页面的json

如何在uniapp中实现图片滤镜效果如何在uniapp中实现图片滤镜效果Jul 04, 2023 am 11:05 AM

如何在uniapp中实现图片滤镜效果在移动应用开发中,图片滤镜效果是一种常见且受用户喜爱的功能之一。而在uniapp中,实现图片滤镜效果也并不复杂。本文将为大家介绍如何通过uniapp实现图片滤镜效果,并附上相关代码示例。导入图片首先,我们需要在uniapp项目中导入一张图片,以供后续滤镜效果的处理。可以在项目的资源文件夹中放置一张命名为“filter.jp

UniApp实现性能监控与瓶颈分析的最佳实践UniApp实现性能监控与瓶颈分析的最佳实践Jul 04, 2023 am 08:46 AM

UniApp实现性能监控与瓶颈分析的最佳实践随着移动应用的快速发展,开发人员对应用性能的需求也日益增加。对于UniApp开发者来说,实现性能监控和瓶颈分析是非常重要的一项工作。本文将介绍UniApp中实现性能监控和瓶颈分析的最佳实践,并提供一些代码示例供参考。一、性能监控的重要性在现代移动应用中,用户体验是非常重要的。性能问题会导致应用加载速度慢、卡顿等问题

UniApp实现启动图与引导图的配置与使用指南UniApp实现启动图与引导图的配置与使用指南Jul 04, 2023 am 11:09 AM

UniApp实现启动图与引导图的配置与使用指南引言:UniApp是一个基于Vue.js开发的跨平台应用开发框架,可通过一套代码实现同时在iOS、Android、H5等多个平台下运行。在移动应用的开发中,启动图与引导图是提升用户体验的关键因素之一。本文将详细介绍UniApp中如何配置和使用启动图与引导图,并附上相应的代码示例。一、配置启动图在UniApp的项目

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.