request-core 多端网络请求

request-core

TarounimpVue 等多端网络请求

目的:实现各多端框架(tarouniAppmpvue 等)统一请求代码。

基于 Promise 对象实现更简单的 request 使用方式,支持请求拦截响应拦截全局配置,为项目迁移到别的框架实现解耦。欢迎为本项目提issus。

安装

依赖包下载

# 使用 npm 安装
$ npm i request-core

# OR 使用 cnpm 安装
$ cnpm i request-core

# OR 使用 yarn 安装
$ yarn add request-core
复制代码

使用

Taro

// app.js
import http from 'request-core/src/taro'
Taro.$http = http

//xxx.js 
//Taro.$http(options={})	或	Taro.$http.get(url,data,options={})
复制代码

uniApp

//main
import http from 'request-core/src/uni'
Vue.prototype.$http = $http;

//xxx.vue 
//this.$http(options={})	或	this.$http.get(url,data,options={})
复制代码

微信小程序weapp(单一端)

首先,你需要将 node_modules 目录下的 request-core 拷贝到 项目根目录 或 需要的目录。

//app.js

import http from './request-core/src/weapp'
wx.$http = http;

App({
	....
})

//xxx.js 
// wx.$http(options={})		或		wx.$http.get(url,data,options={})

复制代码

全局配置

可用的全局配置 baseURLurldataheadermethoddataType和框架自带的其他配置,比如Taro h5 端的配置。

http.config = {
	dataType:'text',
	baseURL:'http://localhost:3000',
	header: {
		"Content-Type": "awe5g45aewg45ewg1",
	},
}
复制代码

请求拦截

http.interceptors.request.use(config=>{
	console.log('请求拦截',config)
	config.data.name = '测试'
	return config
},err=>{
	console.log('拦截请求报错',err)
})

http.interceptors.response.use((res)=>{
	console.log('响应拦截',res)
	return res.data
},(err)=>{
	console.log('拦截响应报错',err)
})
复制代码

局部配置优先级高于全局配置,全局配置优先级高于默认配置。

调用方式1

http({
	url:'users/test3',
	data:{
		name:'111',
		test:'222',
	},
}).then(res=>{
	console.log('请求结果',res)
}).catch(err=>{
	console.log('报错了》》》》',err)
})
复制代码

调用方式2

可用的请求方式 有 OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT

http.get('users/test3',{
    name:'111',
    test:'222',
})
.then(res=>{
    console.log('请求结果',res)
}).catch(err=>{
    console.log('报错了》》》》',err)
})
复制代码

转载于:https://juejin.im/post/5ce63d4ae51d4577523f22eb

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值