为什么使用fly网络请求库
当我们在做微信小程序端的交互的时候,发现jquey、axios这些都无法在小程序中使用,因为小程序中js的运行环境与普通浏览器的运行环境不同,页面的脚本逻辑是在JsCore中运行的,而JsCore中没有xmlhttpRequest对象,所以无法使用它们,同时JsCore无法提供window对象,这也是我们在小程序中无法使用window对象的原因,在这时候我们的主角fly大显身手???
fly是一种可以在微信小程序运行的交互方式,提供统一的 Promise API,轻量且非常轻量,支持请求/响应拦截器,小程序用法:
首先,先使用 npm install flyio,安装fly;
后面在小程序中引入:
var Fly=require("flyio/dist/npm/wx")
var fly=new Fly
1.get请求
fly.get('/user?id=133')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
2.post请求
fly.post('/user', {
name: 'Doris',
age: 24
phone:"18513222525"
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3.拦截器
支持两种。一种是请求拦截器,在请求之前做一些预处理;一种是响应拦截器,在响应获取数据之后做一些处理。
请求拦截器:
fly.interceptors.request.use((request)={
//给所有请求添加自定义header
request.headers["X-Tag"]="flyio";
//打印出请求体
console.log(request.body)
//可以显式返回request, 也可以不返回,没有返回值时拦截器中默认返回request
return request;
})
响应拦截器:
//添加响应拦截器,响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
(response) = {
//只将请求结果的data字段返回
return response.data
},
(err) = {
//发生网络错误后会走到这里
//return Promise.resolve("ssss")
}
)
使用示例:
下载wx.js源码:https://github.com/wendux/fly/tree/master/dist/npm/wx.js
const app = getApp()
var Fly = require("./wx.js") //wx.js为您下载的源码文件
var fly = new Fly();
//添加拦截器
fly.interceptors.request.use((config, promise) => {
//给所有请求添加自定义header
if(false){
config.headers["X-Tag"] = "flyio";
return config;
}
});
//配置请求基地址
// fly.config.baseURL = 'http://gank.io/api/data/%E7%A6%8F%E5%88%A9'
Page({
data: {
},
postFly() {
var data = {};
data.stage_id=1;
data.page=1;
data.limit=2;
fly.post('http://www.qubaobei.com/ios/cf/dish_list.php', data)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
},
testFly() {
//发起get请求
fly.get("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&page=1&limit=2", {
}).then((d) => {
//输出请求数据
console.log(d.data)
//输出响应头
console.log(d.header)
}).catch(err => {
console.log(err.status, err.message)
})
},
onLoad: function() {
// this.testFly();
},
})