flyio使用
Fly.js :基于Promise的、强大的、支持多种JavaScript运行时的http请求库.。可以使用一份http请求代码在浏览器、微信小程序、Weex、Node、React Native、快应用中都能正常运行,同时可以方便配合主流前端框架 。
详细具体用法可移步官网查看文档:https://wendux.github.io/dist/#/doc/flyio/readme
npm安装
npm install flyio --save
在src/utils目录下新建request.js文件。
const Fly = require('flyio/dist/npm/wx')
const service = new Fly()
service.config.baseURL = 'http://xxxx.com:8090/life/app/'
service.config.timeout = 5000
// 添加请求拦截器
service.interceptors.request.use((request) => {
request.headers['X-Tag'] = 'flyio'
console.log(request.body)
wx.showLoading({
title: '加载中'
})
return request
})
// 添加响应拦截器,响应拦截器会在then/catch处理之前执行
service.interceptors.response.use(
(response) => {
wx.hideLoading()
if (response.data.result !== 1) {
wx.showToast({
title: response.data.message,
icon: 'none',
duration: 2000
})
} else {
return response.data
}
},
(err) => {
return Promise.reject(err)
}
)
export default service
使用方式
(1)可以直接在main.js中挂载,全局使用。
import fly from './utils/request'
Vue.prototype.$fly = fly
然后在页面中使用:
this.$fly.request({
method: 'post', // post/get 请求方式
url: '/login',
body: {}
}).then(res => {
console.log(res)
})
(2)也可以单独在src目录下创建api文件。
import Fly from '@/utils/request'
export function getLogin (params) {
return Fly.post('message/operateMessage', params)
}
然后在页面中使用:
import { getLogin } from '@/api/login.js'
login () {
const data = {
userCode: 'WMBL8Aw0RVxL5SH3A7nwzQ==',
type: 'total',
shareid: '201803022a7e66a2c0d148afa3af52d586b6266c'
}
const params = this.$qs.stringify(data)
console.log(params)
getLogin(params).then(res => {
console.log(res)
})
}