Supporting request forwarding and Promise based HTTP client for all JavaScript runtimes.
Chinese documentation : 中文文档
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
|---|---|---|---|---|---|
| ✔ | ✔ | ✔ | ✔ | ✔ | > 8 |
|
|
|
|
|
Currently the platforms that fly.js supported include Node.js 、WeChat Mini Program 、Weex 、React Native 、Quick App and the browers, all JavaScript runtimes of these are different. More platforms are supporting...
Fly.is locates to be the ultimate solution for Javascript http requests. That is to say, in any environment that can execute Javascript, as long as it has the ability to access the network, Fly can run on it and provide unified APIs. At the same time, keep lightweight on the browser side.
You can find the Fly documentation on the offical website.
Using npm
npm install flyio
Using CDN (on browsers)
<script src="https://cdn.jsdelivr.net/npm/flyio/dist/fly.min.js"></script>
UMD (on browsers)
https://cdn.jsdelivr.net/npm/flyio/dist/umd/fly.umd.min.js
The entry files of different JavaScript Runtimes may be different, you can refer on the below, but the entries of Browsers, Node, and React Native are the same。each requirement ways of these platforms are as follows:
javascript
//for Browsers, Node, and React Native
var fly=require("flyio")
The above method requires the default instance of Fly, and you can also create an Fly instance by yourself:
javascript
// for browsers and React Native
var Fly=require("flyio/dist/npm/fly")
// for Node
//var Fly=require("flyio/src/node")
var fly=new Fly;
javascript
var Fly=require("flyio/dist/npm/wx")
var fly=new Fly
If your project does not use NPM to manage dependencies, you can download the source code directly to your project 。The download links are wx.js or wx.umd.min.js . Download any one, save it to your project directory (assuming named "lib") , and then requiring:
javascript
var Fly=require("../lib/wx")
var fly=new Fly;
On Quick App, Fly relies on the fetch module, which needs to be defined in the manifest.json first:
java
"features": [
...
{"name": "system.fetch"}
]
And then create Fly instance:
javascript
var fetch = require("@system.fetch")
var Fly=require("flyio/dist/npm/hap")
var fly=new Fly(fetch)
javascript
var Fly=require("flyio/dist/npm/weex")
var fly=new Fly
After the requirement, you can make the global configuration and add the interceptor to fly , and peform network request with fly.
The following example, if not specified, can be executed in all JavaScript Runtimes.
GET requestvar fly=require("flyio")
// Make a request for a user with a given ID, and the parameter is passed directly in URL
fly.get('/user?id=133')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// The parameter is passed by a object
fly.get('/user', {
id: 133
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
POST requestfly.post('/user', {
name: 'Doris',
age: 24
phone:"18513222525"
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
POST request with Url paramsfly.get("../package.json", "xxx=5", {
params: {
c: 1
}
}
)
The final url is "package.json?c=1&xxx=5".
function getUserRecords() {
return fly.get('/user/133/records');
}
function getUserProjects() {
return fly.get('/user/133/projects');
}
fly.all([getUserRecords(), getUserProjects()])
.then(fly.spread(function (records, projects) {
// Both requests are now complete
}))
.catch(function(error){
console.log(error)
})
requestfly.request("/test",{hh:5},{
method:"post",
timeout:5000 // Set timeout to 5 seconds
})
.then(d=>{ console.log("request result:",d)})
.catch((e) => console.log("error", e))
URLSearchParamsconst params = new URLSearchParams();
params.append('a', 1);
fly.post("",params)
.then(d=>{ console.log("request result:",d)})
Note that
URLSearchParamsis not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).
FormData var formData = new FormData();
var log=console.log
formData.append('username', 'Chris');
fly.post("../package.json",formData).then(log).catch(log)
Note that
FormDatais not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment). And there are some differences on the way to support formData in node environment. Please click here for more details
fly.get("/Fly/v.png",null,{
responseType:"arraybuffer"
}).then(d=>{
//d.data is a ArrayBuffer instance
})
In browser, the value of responseType can be one of "arraybuffer" or "blob". In node, you can just set it as "stream"
You can intercept requests or responses before they are handled by then or catch.
// Add a request interceptor
fly.interceptors.request.use((request)=>{
// Do something before request is sent
request.headers["X-Tag"]="flyio";
console.log(request.body)
// Complete the request with custom data
// return Promise.resolve("fake data")
})
// Add a response interceptor
fly.interceptors.response.use(
(response) => {
// Do something with response data .
// Just return the data field of response
return response.data
},
(err) => {
// Do something with response error
//return Promise.resolve("ssss")
}
)
The structures of the request object in request interceptor.
{
baseURL, //base url
body, // request parameters
headers, //custom request headers
method, // http request method
timeout, // request time
url, // request url (or relative path)
withCredentials, // determine whether sending thirdparty cookies in cross-domain request
... // custom field defined in options
}
The structures of the response object in response interceptor.
{
data, //response data
engine, //http engine,In browser,it's a instance of XMLHttpRequest.
headers, //response headers
request //the origin request object
}
If you may need to remove an interceptor later, just set it to null.
fly.interceptors.request.use(null)
fly.interceptors.response.use(null,null)
Now, you can perform async task in interceptors !
Let's see an example:
because of security reasons, we need all the requests to set up a csrfToken in the header, if csrfToken does not exist, we need to request a csrfToken first, and then perform the network request, because the request csrfToken progress is asynchronous, so we need to execute this async request in request interceptor. the code is as follows:
var csrfToken="";
var tokenFly=new Fly();
var fly=new Fly();
fly.interceptors.request.use(function (request) {
//if csrfToken does not exist, we need to request a csrfToken first
if(!csrfToken) {
// locking the current instance, let the incomming request task enter a
// queue before they enter the request interceptors.
fly.lock();
//Using another fly instance to request csrfToken.
//If use the same fly instance, there may lead a infinite loop:
//(The request will go to the interceptor first, and then
//enter the interceptor again when launching the new request
//in the interceptor....)
return tokenFly.get("/token").then((d)=>{
request.headers["csrfToken"]=csrfToken=d.data.data.token;
//only return the origin `request` object can make the http request continue.
// otherwise, the return data will be teated as "response" data.
return request
}).finally(()=>{
//fly.clear(); //clear the request queue
// unlock the current instance, flush the request queue.
fly.unlock()
})
}else {
request.headers["csrfToken"]= csrfToken;
//This line can be omitted.
//If the interceptor doesn't return value, `request` will be used by default.
return request
}
})
Note:
fly.lock() . Once the fly instance is locked, the incomming request task maked by it will be hang up and enter a queue before they enter the request interceptors, you can call fly.unlock() to continue the requests or call fly.clear() to cancel the requests in the queue.request object passed by interceptor at the final , the origin http request will be continued. And you can also make an async task in the response interceptor. More information about interceptors and examples refer to flyio interceptor.