Taro
、uni
、mpVue
等多端網絡請求javascript
目的:實現各多端框架(
taro
、uniApp
、mpvue
等)統一請求代碼。vue
基於 Promise 對象實現更簡單的 request 使用方式,支持請求攔截
、響應攔截
和全局配置
,爲項目遷移到別的框架實現解耦。歡迎爲本項目提issus。java
# 使用 npm 安裝
$ npm i request-core
# OR 使用 cnpm 安裝
$ cnpm i request-core
# OR 使用 yarn 安裝
$ yarn add request-core
複製代碼
// app.js
import http from 'request-core/src/taro'
Taro.$http = http
//xxx.js
//Taro.$http(options={}) 或 Taro.$http.get(url,data,options={})
複製代碼
//main
import http from 'request-core/src/uni'
Vue.prototype.$http = $http;
//xxx.vue
//this.$http(options={}) 或 this.$http.get(url,data,options={})
複製代碼
首先,你須要將 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={})
複製代碼
可用的全局配置
baseURL
、url
、data
、header
、method
、dataType
和框架自帶的其餘配置,好比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
http({
url:'users/test3',
data:{
name:'111',
test:'222',
},
}).then(res=>{
console.log('請求結果',res)
}).catch(err=>{
console.log('報錯了》》》》',err)
})
複製代碼
可用的請求方式 有
OPTIONS
,GET
,HEAD
,POST
,PUT
,DELETE
,TRACE
,CONNECT
npm
http.get('users/test3',{
name:'111',
test:'222',
})
.then(res=>{
console.log('請求結果',res)
}).catch(err=>{
console.log('報錯了》》》》',err)
})
複製代碼