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

HTML+CSS+JS realizes the scrolling gradient effect of the navigation bar

Table of contents First look at the effect: accom...

Solution to the problem of passing values ​​between html pages

The first time I used the essay, I felt quite awkw...

Solve the Linux Tensorflow2.0 installation problem

conda update conda pip install tf-nightly-gpu-2.0...

Nginx rtmp module compilation arm version problem

Table of contents 1. Preparation: 2. Source code ...

Learn Vue middleware pipeline in one article

Often when building a SPA, you will need to prote...

Steps to deploy ingress-nginx on k8s

Table of contents Preface 1. Deployment and Confi...

MySQL 5.6.24 (binary) automatic installation script under Linux

This article shares the mysql5.6.24 automatic ins...

Analysis of two implementation methods for adding static routing in Linux

Command to add a route: 1.Route add route add -ne...

Detailed explanation of the failure of MySQL to use UNION to connect two queries

Overview UNION The connection data set keyword ca...

How to build and deploy Node project with Docker

Table of contents What is Docker Client-side Dock...

Summary of several common logs in MySQL

Preface: In the MySQL system, there are many diff...

Problems with using wangeditor rich text editing in Vue

wangEditor is a web rich text editor developed ba...

Introduction to JavaScript Number and Math Objects

Table of contents 1. Number in JavaScript 2. Math...