How to use axios to make network requests in React Native

How to use axios to make network requests in React Native

In front-end development, there are many ways to complete data requests, such as Ajax, jQuery ajax, axios, and fetch. However, with the development of technology, the two methods we can see now are basically axios and fetch.

Axios is a Promise-based Http network library that can run on the browser side and Node.js. Network requests of Vue applications are basically completed using it. Axios has many excellent features, such as support for request interception and response, request cancellation, automatic JSON conversion, client-side defense against XSRF, etc.

Before using axios, you need to install the axios plug-in in the project. The installation command is as follows.

//npm 
npm install axios --save
//yarn
yarn add react-native-axios 

As an excellent network request library, axios supports basic requests such as GET, POST, DELET and PUT. For example, when using axios to make a GET request, you can use the axios.get() method and axios(config { ... }), as shown below.

axios.get('/getData', {
    params: { 
      id: 123
    }
  }).then(function (response) {
    console.log(response);
  })

axios({
  method: 'GET',
  url: '/getData',
  params: {
    id: 123,
  }
}).then(function (response) {
    console.log(response);
}); 

It can be seen that if axios is used directly for network requests, a lot of redundant code will be generated. Therefore, in the actual development process, some encapsulation of axios requests is also required to facilitate later use, as shown below.

It can be seen that if axios is used directly for network requests, a lot of redundant code will be generated. Therefore, in the actual development process, some encapsulation of axios requests is also required to facilitate later use, as shown below.

const request = axios.create({
  transformResponse: [
    function (data) {
      return data;
    },
  ],
});

const defaultOptions = { //Processing default configuration url: '',
  userAgent: 'BIZSTREAM Library',
  authentication:
    integration:
      access_token: undefined,
    },
  },
};

class Bizstream {
  init(options) {
    this.configuration = {...defaultOptions, ...options};
    this.base_url = this.configuration.url;
    this.root_path = '';
  }

  post(path, params, data, type = ADMIN_TYPE) {
    return this.send(path, 'POST', params, data, type);
  }

  get(path, params, data, type = ADMIN_TYPE) {
    return this.send(path, 'GET', params, data, type);
  }

  send(path, method, params, data, type, headersOption) {
    const url = `${this.base_url}${this.root_path}${path}`;
    const headers = {
      'User-Agent': this.configuration.userAgent,
      'Content-Type': 'application/json',
      ...headersOption,
    };

    return new Promise((resolve, reject) => {
      request({url, method, headers, params, data}).then(response => {
        .... //Process the returned result});
    });
  }
}

export const bizStream = new Bizstream();

After encapsulation, it is much more convenient to make network requests, and we also process some common return results at the network layer. In actual use, developers only need to pass in the required parameters as required, and then process the returned results through the asynchronous function, as shown below.

//GET request const hotMovie='';
const data = await apiRequest.get(hotMovie);
//POST request let baseUrl = '';
let param = {
   pageNumber: 0,
   cityCd: 31,
 };
const data = await apiRequest.post(baseUrl, param);

This is the end of this article about how to use axios to make network requests in React Native. For more information about React Native network requests, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of axios encapsulation and API interface management in React project
  • Do you know the axios module in react?
  • Axios module in React and how to use it
  • React axios cross-domain access to one or more domain names
  • React uses axios to encapsulate API network requests

<<:  How to run multiple MySQL instances in Windows

>>:  How to implement ansible automated installation and configuration of httpd in Linux system

Recommend

CentOS 6.5 configuration ssh key-free login to execute pssh command explanation

1. Check and install pssh, yum list pssh 2. Becau...

Implementation of MySQL5.7 mysqldump backup and recovery

MySQL backup Cold backup:停止服務進行備份,即停止數據庫的寫入Hot ba...

Examples of using the or statement in MySQL

1. The use of or syntax in MySQL, and the points ...

Understand CSS3 FlexBox elastic layout in 10 minutes

Basic Introduction Features Flexbox is a CSS disp...

Detailed explanation of html printing related operations and implementation

The principle is to call the window.print() metho...

HTML form tag tutorial (5): text field tag

<br />This tag is used to create a multi-lin...

Detailed explanation of how Zabbix monitors the master-slave status of MySQL

After setting up the MySQL master-slave, you ofte...

MySQL 5.7 generated column usage example analysis

This article uses examples to illustrate the usag...

MySQL Workbench download and use tutorial detailed explanation

1. Download MySQL Workbench Workbench is a graphi...

Recommend a cool interactive website made by a front-end engineer

Website link: http://strml.net/ By Samuel Reed Ti...

Detailed explanation of LVM seamless disk horizontal expansion based on Linux

environment name property CPU x5650 Memory 4G dis...

Tutorial on how to deploy LNMP and enable HTTPS service

What is LNMP: Linux+Nginx+Mysql+(php-fpm,php-mysq...

Integration practice of Vue+Element background management framework

Table of contents Vue+ElementUI background manage...