request-core 多端網絡請求

request-core

TarounimpVue 等多端網絡請求javascript

目的:實現各多端框架(tarouniAppmpvue 等)統一請求代碼。vue

基於 Promise 對象實現更簡單的 request 使用方式,支持請求攔截響應攔截全局配置,爲項目遷移到別的框架實現解耦。歡迎爲本項目提issus。java

安裝

依賴包下載

# 使用 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 拷貝到 項目根目錄 或 須要的目錄。node

//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 端的配置。git

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)
})
複製代碼

局部配置優先級高於全局配置,全局配置優先級高於默認配置。github

調用方式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, CONNECTnpm

http.get('users/test3',{
    name:'111',
    test:'222',
})
.then(res=>{
    console.log('請求結果',res)
}).catch(err=>{
    console.log('報錯了》》》》',err)
})
複製代碼
相關文章
相關標籤/搜索