Fly.js
Fly.js is a powerful lightweight javascript http request library, which supports both browser and node environments. It can run in any network-capable javascript runtime environment through adapters. At the same time, fly.js has some advanced methods, such as global ajax interception, support request redirection in web app, etc. It will give you enough surprise if you look at it patiently.
Next, I'll give you a few articles on fly.js's advanced gameplay. This is the first, a whole introduction. If you are interested, you can go. fly official website Learn more.
brief introduction
Fly.js is a promise-based, lightweight and powerful Javascript http network library. It has the following characteristics:
- Provide a unified Promise API.
- Support browser environment, lightweight and very lightweight.
- Support Node environment.
- Support request/response interceptors.
- Automatic conversion of JSON data.
- It supports switching the underlying Http Engine and can easily adapt to various operating environments.
- The browser side supports global Ajax interception.
- When H5 pages are embedded in native APP, it supports forwarding http requests to Native. Supports direct request for pictures.
- It is highly customizable, removable and assembled.
Location and Target
Fly's location is the ultimate solution for Javascript http requests. That is to say, in any environment that can execute Javascript, Fly can run on it and provide a unified API as long as it has the ability to access the network.
Contrast with axios and Fetch
For a detailed comparison, please refer to the article on Flio.com Contrast with axios and Fetch .
install
Using NPM
npm install flyio
Use a CDN
<script src="https://unpkg.com/flyio/dist/fly.min.js"></script>
UMD
https://unpkg.com/flyio/dist/fly.umd.min.js
Example
The following examples can be executed in both browser and node environments without special instructions.
Launching GET requests
var fly=require("flyio")
//Getting information through user id, parameters are written directly in url
fly.get('/user?id=133')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
//query parameters are passed through objects
fly.get('/user', {
id: 133
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Initiate POST requests
fly.post('/user', {
name: 'Doris',
age: 24
phone:"18513222525"
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Initiate multiple concurrent requests
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 completed
}))
.catch(function(error){
console.log(error)
})
Initiate requests directly through the request interface
//Initiate a post request by calling the request function directly
fly.request("/test",{hh:5},{
method:"post",
timeout:5000 //Set timeout to 5s
})
.then(d=>{ console.log("request result:",d)})
.catch((e) => console.log("error", e))
Send URLSearchParams
const params = new URLSearchParams();
params.append('a', 1);
fly.post("",params)
.then(d=>{ console.log("request result:",d)})
Note: URLSearchParams do not exist in Node environment. Each browser supports URLSearchParams differently, so be careful when using it.
Send FormData
var formData = new FormData();
var log=console.log
formData.append('username', 'Chris');
fly.post("../package.json",formData).then(log).catch(log)
Note: Fly currently supports formData only in browser environments that support formData. There are slightly different ways to support formData in node environments. Details are stamped here. Enhanced API under Node .
Request binary data
fly.get("/Fly/v.png",null,{
responseType:"arraybuffer"
}).then(d=>{
//d.data is an example of ArrayBuffer
})
Note: The responseType value can be one of the "arraybuffer" or "blob" values in browsers. Under node, you only need to set it to "stream".
Interceptor
Fly supports a request/response interceptor, which can do some preprocessing before the request is initiated and after the response data is received.
//Add request interceptor
fly.interceptors.request.use((config,promise)=>{
//Add a custom header to all requests
config.headers["X-Tag"]="flyio";
//The request can be terminated directly through promise.reject / resolution
//promise.resolve("fake data")
return config;
})
//Add a response interceptor, which executes before then/catch processing
fly.interceptors.response.use(
(response,promise) => {
//Return only the data field of the request result
return response.data
},
(err,promise) => {
//Come here after a network error
//promise.resolve("ssss")
}
)
If you want to remove the interceptor, just set the interceptor to null:
fly.interceptors.request.use(null)
fly.interceptors.response.use(null,null)
Node
Fly provides a unified Promise API in both browser and Node environments. This means that whether you are web or node development, you can initiate HTTP requests in the same way. However, due to the differences between node and browser environment, Fly provides some enhanced APIs in addition to supporting basic APIs in Node environment. These APIs mainly involve many powerful functions, such as file download, multi-file upload, http proxy, and so on. For more information, please refer to them. Enhanced API under Node
error handling
After the request fails, catch captures err as an instance of Error with two fields:
{
message:"Not Find 404", //Error message
status:404 //If the server is accessible, the http request status code. Network exception time is 0, network timeout time is 1
}
Error code | Meaning |
---|---|
0 | network error |
1 | request timeout |
2 | File download succeeded, but save failed. This error only occurs in node environment. |
=200
|
http request status code |
Request configuration options
Configurable options:
{
headers:{}, //http request header,
baseURL:"", //Request base address
timeout:0,//There is no timeout limit when the timeout time is 0.
withCredentials:false //Whether to send cookie s across domains
}
Configuration supports instance-level configuration and single request configuration
Instance-level configuration
Instance-level configuration can be used for all requests initiated by the current Fly instance
//Define common headers
fly.config.headers={xx:5,bb:6,dd:7}
//setsockopt
fly.config.timeout=10000;
//Setting Request Base Address
fly.config.baseURL="https://wendux.github.io/"
Single request configuration
When you need to configure a single request, you need to use the request method, which is only valid for the current request.
fly.request("/test",{hh:5},{
method:"post",
timeout:5000 //Set timeout to 5s
})
Note: If single configuration and instance configuration conflict, single request configuration will be preferred.
API
fly.get(url, data, options)
Initiate get request, url request address, data request data, in the browser environment type can be:
String|Json|Object|Array|Blob|ArrayBuffer|FormData
options configures items for requests.
fly.post(url, data, options)
Initiate a post request with the same meaning as fly.get.
fly.request(url, data, options)
To initiate a request, the parameter implies the same thing. When using this API, you need to specify the method of options:
//GET request
fly.request("/user/8" null, {method:"get"})
//DELETE request
fly.request("/user/8/delete", null, {method:"delete"})
//PUT request
fly.request("/user/register", {name:"doris"}, {method:"PUT"})
......
request is suitable for RESTful API Used in the scenario of uuuuuuuuuuu
fly.all([])
Multiple concurrent requests are initiated with a promise array as the parameter; then is invoked when all requests succeed, and catch is invoked whenever one fails.
Create Fly instances
For ease of use, after introducing the Flio library, a default instance is created. Generally, most requests are sent through the default instance, but in some scenarios, multiple instances are required (possibly using different configuration requests). You can manually create a new one:
//npm, node environment
var Fly=require("fio/dist/fly") //Be careful! At this point, "fio/dist/fly" is introduced.
var nFly=new Fly();
//Direct new when CDN is introduced
var nFly=new Fly();
Http Engine
Fly introduces the concept of Http Engine. The so-called Http Engine is the engine that actually initiates http requests. This is usually XML Http Request in browsers. In Node environment, it can be implemented with any library/module that can initiate network requests. Fly is free to replace the underlying Http Engine. In fact, Fly supports both browser and Node environments by replacing Http Engine. However, Http Engine is not limited to Node and browser environments, but also can be Android, ios, electron and so on. Because of these, Fly has a very unique and powerful function - Request redirection. Based on request redirection, we can achieve some very useful functions, such as redirecting all HTTP requests embedded in APP to Native, then unifying network requests on the end (Android, ios), cookie management, certificate verification, etc., details stamp. Fly Http Engine
Global Ajax interception
In browsers, global Ajax requests can be intercepted by replacing XMLHttpRequest with Fly engine, regardless of the network library used by the upper layer.
volume
In the browser environment, the size of a library is very important. Fly has done a good job in this area. It keeps its powerful function while keeping its body in the best shape. min is only about 4.6K, and GZIP is less than 2K after compression, which is a quarter of the volume of axios.
Finally
If you feel Fly is useful to you, welcome star. github: https://github.com/wendux/fly
Add a sentence
Recruitment front-end, Recruitment front-end, Recruitment front-end! Recently, I have been looking for a job or want to change my job, and I am sending Demons-du. Location: Beijing