Using axios to encapsulate api network requests in react projects

foreword

I recently wrote a react project using axios for request encapsulation. I will record it here, I hope it can help beginners

Ready to work

You need to use axios to make requests, so make sure you have installed axios first, and check the package.json file.
insert image description here
If not, please install axios first

npm install axios

Start packaging axios

First, create a new axios folder in the src directory. Here we create two new files, config.js and request.js

config.js

This file is used for basic configuration and to distinguish the development environment:

  1. Define devBaseUrl development environment and proBaseUrl production environment
  2. Use process.env to distinguish between development and production environments, it returns an environment information containing the user
  3. Finally set the timeout
const devBaseUrl = 'http://api.k780.com/'
const proBaseUrl = 'http:xxx//xxxx.xx.com'

export const BASE_URL = process.env.NODE_ENV === 'development' ? devBaseUrl : proBaseUrl

export const TIMEOUT = 5000

request.js

Store the corresponding encapsulation methods and interceptors:

  1. First import the BASE_URL, TIMEOUT we wrote above in axios and config
  2. Define instance = axios.create({ }), which stores objects
  3. Write a request interceptor, in which you can do token verification and other operations
import axios from 'axios'
import {
    
     BASE_URL, TIMEOUT } from './config'

const instance = axios.create({
    
    
    baseURL: BASE_URL,
    timeout: TIMEOUT
})

// 请求拦截器
instance.interceptors.request.use(config => {
    
    
    console.log('被拦截做一些操作')
    return config
}, err => {
    
    
    return err
})

export default instance

make a request

After completing the above encapsulation, we can perform the request operation. When we come to the page to be used,
first import the request file we just wrote:

import request from '../../axios/request'

What I am requesting here is a weather interface on the Internet. The address has been written in the devBaseUrl in the config.js file above.
For the api request, we make an asynchronous request in the componentDidMount() life cycle:

  1. Async operations with async await
  2. Use data to receive the result of the request, and write the params parameters required by the request in the request
  3. Finally, print the data to see the result, and then use setState to modify the value
async componentDidMount() {
    
    
    const data = await request({
    
    
      // 参数
      params: {
    
    
        app: 'weather.today',
        weaId: 248,
        appkey: 10003,
        sign: 'b59bc3ef6191eb9f747dd4e83c99f2a4',
        format: 'json'
      }
    })
    console.log(data)
    this.setState({
    
    weather: data.data.result.weather})
  }

Check the printed result:
you can see the requested data, which means that the request is successful.
insert image description here
Here I am using the free interface of online weather. For the use of the interface, you can check the link Nowapi

Ok, this article is over here. If it is helpful to you, you can like, follow and support it. Thank you~~
I will bring more front-end knowledge content in the future.

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/123693319