搜索
首页web前端uni-appuniapp如何实现网络请求封装

uniapp如何实现网络请求封装

Dec 21, 2020 pm 05:25 PM
uniapp请求封装

uniapp实现网络请求封装的方法:首先实现初始请求;然后新建【request.js】文件,代码为【return new Promise((resolved, rejected) => {uni.request..】;最后进行优化即可。

uniapp如何实现网络请求封装

本教程操作环境:windows7系统、uni-app2.5.1版本,该方法适用于所有品牌电脑。

推荐(免费):uni-app开发教程

uniapp实现网络请求封装的方法:

一、uniapp初始请求使用方式如下:

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);
  }
});

二、我们先通过Promise进行一次简单封装,新建request.js文件:

//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;

三、最后我们在上一步基础上再一次优化。

//把配置项单独处理
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;

四、现在我们在页面中使用。

1、新建pages页面。

目录如下

┌─common

│ ├─request.js //请求

┌─pages

│ ├─index

│ │ └─api.js //api列表

│ │ └─index.vue //页面文件

├─static

├─store

│ ├─index.js //vuex

├─main.js

├─App.vue

├─manifest.json

└─pages.json

2、配置api列表。api.js //api列表

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

3、页面中使用

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

以上是uniapp如何实现网络请求封装的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具