what is axios
When an ancient browser page requests data from the server, because the data of the entire page is returned, the page will be forced to refresh, which is not very user-friendly. And we only need to modify part of the data of the page, but the data of the entire page is sent from the server side, which consumes a lot of network resources. And we only need to refresh part of the data of the page, and do not want to refresh the entire page. So a new technology, Ajax (Asynchronous JavaScript and XML) for asynchronous network request is produced, which can exchange a small amount of data with the backend server, so that the webpage can be updated asynchronously. This means that some parts of the web page can be updated without reloading the entire page.
However, because the native XMLHttpRequest API in the browser is difficult to use, there are more javascript frameworks for implementing ajax, such as jQuery, Dojo, YUI and so on that we are familiar with. Today, a lightweight framework called axios has gradually come to the fore. At present, its record in github has reached Fork9.6k+ and Star94k+. It is also a package of native XHR in essence, but it is the implementation version of Promise, which conforms to the latest ES specification. , has the following characteristics:
● Create XMLHttpRequests from the browser
● Create http requests from node.js ● Support Promise API
● Intercept request and response ● Convert request data and response data ● Cancel request ● Automatically convert JSON data

Using axios in OpenHarmony app

We can see that axios can be used both in the browser and in Nodejs, and now with the development of OpenHarmony ArkUI, axios has a new use, that is, it can be used in the application of the OpenHarmony standard system: available It is used for network requests and uploading and downloading files, and fully inherits the native usage and all features of axios.
Yes, you read that right, axios is indeed available on OpenHarmony. The following is a brief introduction to how to use axios in the OpenHarmony application.
first step:
Download and install the OpenHarmony axios third-party components in the application of the OpenHarmony standard system.

 npm install @ohos/axios –save

For more information on OpenHarmony npm environment configuration, please refer to the installation tutorial on how to install the OpenHarmony npm package.
( https://gitee.com/openharmony-tpc/docs/blob/master/OpenHarmony_npm_usage.md )
Step 2:
In the page, introduce axios.

 import axios from "@ohos/axios";

third step:
axios can be used as a function to initiate asynchronous requests directly, or it can be used as an object to initiate asynchronous requests using its get/post methods.
As a function, a post request is directly initiated, and the request result is obtained through promise.

 let url = 'http://www.xxx.xxx';
    axios({
      method: "post",
      url: url,
      data:{
        catalogName: "doc-references",
        language: "cn",
        objectId: "js-apis-net-http-0000001168304341",
      }
    })
      .then(res => {
        console.info('post result:' + JSON.stringify(res.data.value.breadUrl))
      })
      .catch(error => {
        console.info('post error!')
      })

As an object, use its get/post methods to initiate asynchronous requests

 const test= axios.create({(                          
  baseURL:'http://xxxx'
});
test.get('/xxxx').then(response=>{})

axios interceptor

Generally, when using axios, the function of interceptor is used, which is generally divided into two types: request interceptor and response interceptor.
● The request interceptor performs necessary operations before the request is sent, such as adding a unified cookie, adding verification to the request body, setting the request header, etc., which is equivalent to an encapsulation of the same operation in each interface;
● The response interceptor is the same, and the response interceptor also has the same function, but after the request is responded, some processing of the response body, usually the unified data processing, etc., is often used to judge the login failure and so on.

The interceptor of axios is very useful. Axios' interceptors are divided into request interceptors and response interceptors, both of which can be set up for multiple request or response interceptors. Each interceptor can set two interception functions, one for successful interception and one for failed interception. After calling axios.request(), the requested configuration will first enter the request interceptor. Normally, the successful interception function can always be executed. If there is an exception, it will enter the failed interception function and will not initiate the request; after the request response is called and returned, It will enter the response success interception function or the response failure interception function according to the response information.
for example
1. Add a request interceptor

 axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

2. Add a response interceptor

 axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

axios upload and download files

Using axios, you can also upload and download files in OpenHarmony, and get the progress of uploading and downloading.
upload files:

 import  axios from '@ohos/axios'
import { FormData } from '@ohos/axios'

var formData = new FormData()
formData.append('file', 'internal://cache/blue.jpg')

// 发送请求
axios.post('http://www.xxx.com/upload', formData, {
   headers: { 'Content-Type': 'multipart/form-data' },
   context: getContext(this),
   onUploadProgress:(uploadedSize: number, total:number):void=> {
      console.info(Math.ceil(uploadedSize/total * 100) + '%');
   },
}).then((res) => {
   console.info("result" + JSON.stringify(res.data));
}).catch(error => {
   console.error("error:" + JSON.stringify(error));
})

download file:

 axios({
   url: 'http://www.xxx.com/blue.jpg',
   method: 'get',
   context: getContext(this),
   filePath: filePath ,
   onDownloadProgress:  (receivedSize: number, total:number):void=> {
       console.info(Math.ceil( receivedSize/total * 100 ) + '%');
   },
   }).then((res)=>{
      console.info("result: " + JSON.stringify(res.data));
   }).catch((error)=>{=
      console.error(t"error:" + JSON.stringify(error));
   })

In addition to the above features, the default configuration of axios, cancellation requests and other features can continue to be used on OpenHarmony. In addition, from the npm official website, you can see that 8000+ third-party components depend on axios. Now that axios supports OpenHarmony, more third-party components will also be able to run on OpenHarmony.

How to port axios to run on OpenHarmony?

Having introduced so many usages of axios, I believe that the old front-end axios fans can't wait to experience it. But maybe you will be curious, why does axios run on OpenHarmony? Doesn't it just support browsers and Nodejs?
For in-depth interpretation of this piece, you need to understand the implementation principle of the axios framework. To put it simply, ohos/axios relies on the three-party components of the open source community axios, and implements ohadapter according to the existing framework of axios, that is, it adapts network calls in OpenHarmony and exposes the original objects of axios, so it can guarantee the api and features of axios are fully inherited. You can go further to openharmony-tpc to see the implementation of its source code.
As shown in the figure below, the blue one on the right is the open source community of the native axios, and the green one on the left is the OpenHarmony axios three-party component, which only implements an adaptation module of OpenHarmony, and does not modify a line of code of the native community.

Summarize

In this issue, the axios component based on OpenHarmony API9 will be introduced to you. Its source code has been open sourced at " https://gitee.com/openharmony-sig/axios ", and you are welcome to use and submit Issues. To learn more about the three-party component dynamics, please pay attention to the three-party component resource summary, more excellent components are waiting for you to discover!


OpenHarmony开发者
160 声望1.1k 粉丝

OpenHarmony是由开放原子开源基金会(OpenAtom Foundation)孵化及运营的开源项目,