Summary of changes in the use of axios in vue3 study notes

Summary of changes in the use of axios in vue3 study notes

Before using axios, you need to install it first.

yarn add axios
 
npm install axios
 
bower install axios
 
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

The four installation methods above can be selected according to the project you created.

1. Basic use of axio

First create a component and import axios to test whether the import is successful! Write the following code:

import axios from "axios"
import { onMounted } from "vue"
export default {
 setup(){
  onMounted(()=>{
   axios({
    url:'https://xxxxxx.net/hj/mp/banner/l'
   })
  })
 }
}

onMounted is a lifecycle hook function. When the page is loaded, this network request will be called. The axios method does not set the network request method. The default is a GET request.

When I opened the service and checked the network request, I found that the request failed:

Error content: Access to XMLHttpRequest at 'https://xxxxx/hj/mp/banner/l' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

It indicates a cross-domain problem.

2. How to solve cross-domain problems?

Use proxy to solve this problem, create a new vue.config.js file and add the configuration:

module.exports={
 devServer:{
  proxy:{
   '/api':{
    target:'https://xxxxx.net',
    changeOrigin:true,
    pathRewrite:{
     '^/api':''
    }
   }
  }
 }
}

It's embarrassing when I refresh the page to check the effect. The requested address is completely correct, but it keeps prompting 404 Address not found.

The project in vue2 has normal request, but it is 404 in vue3.

At the network request, add global configuration and delete the domain name in the URL of the request.

axios.defaults.baseURL = '/api'
axios.defaults.headers.post['Content-Type'] = 'application/json'
 axios({
  url:'/hj/mp/banner/l'
})

After the modification is completed, the network request for refreshing the page becomes successful.

3. Packaging

I haven't used a third-party library once. The most talked about thing is how to encapsulate it and how to use it after encapsulation. Isn't it better to use it directly?

I tell you very clearly that you are still too young...you will remember it after suffering a few more losses. The biggest advantage of encapsulation is that if there is a bug in the third-party framework or the third party needs to be changed, you only need to modify one place to complete the modification. It is easy to maintain, has a small workload, and is not easy to miss.

Since there are many axios request methods, there can be multiple types of encapsulation.

Method 1:

import axios from 'axios'
 
//Global configuration axios.defaults.baseURL = "/api"
axios.defaults.timeout = 5000
 
//Interceptor axios.interceptors.request.use(config=>{
 return config
},error=>{
 return Promise.error(error)
})
axios.interceptors.response.use(response=>{
 return response.data
},error=>{
 return Promise.error(error)
})
 
export function request(url='',params={},type='POST'){
 //Set the default value of url params type return new Promise((resolve,reject)=>{
  let promise
  if( type.toUpperCase()==='GET' ){
   promise = axios({
    url,
    params
   })
  }else if( type.toUpperCase()=== 'POST' ){
   promise = axios({
    method:'POST',
    url,
    data:params
  })
  }
    //Processing return promise.then(res=>{
   resolve(res)
  }).catch(err=>{
   reject(err)
  })
 })
}
 
//Call import {request} from '../network/request.js' when using
export default {
 mounted(){
  request('/hj/mp/banner/l').then(res=>{
   console.log(res);
  }).catch(err=>{
   console.log(err);
  })
 }
}

Since axios returns a promise object itself, we don’t need to instantiate a promise object for the outer layer, making encapsulation simpler.

Method 2:

import axios from 'axios'
 
//Global configuration axios.defaults.baseURL = "/api"
axios.defaults.timeout = 5000
 
export function request(config){
 const instace = axios.create({
  timeout:50000,
  method:'post'
 })
 
  //Request interception instace.interceptors.request.use(config=>{
  return config
 },err=>{})
 //Response interception instace.interceptors.response.use(res=>{
  return res.data
 },err=>{
  // Error handling })
 return instace(config)
}
//Call import {request} from './request' when using
request({
 url:'/hj/mp/banner/l',
}).then(res=>{
 console.log(res);
}).catch(err=>{
 console.log(err);
})

There are many ways to encapsulate axios. If you are interested, you can go to the axios document to learn more and try to encapsulate one yourself, or save it and copy it directly for use in the future without the effort of encapsulating it.

4. Global reference to axios

The above encapsulated request method can be referenced globally so that it can be used in any file in the project.

Add global properties in main.js

const app = createApp(App)
app.config.globalProperties.$http = request
app.mount('#app')

The order of the above three cannot be adjusted!

When used within a component:

import { defineComponent, getCurrentInstance ,onMounted } from "vue"
export default defineComponent ({
 setup(props,ctx){
  const { proxy } = getCurrentInstance()
  onMounted(()=>{
   console.log(proxy);
   proxy.$http('/hj/mp/banner/l').then(res=>{
    console.log(res);
   })
  })
 }
})

Congratulations to you for making it to the end. This is the only thing that has changed in the use of axios in vue3.

This is the end of this article about the changes in the use of axios in the vue3 learning notes. For more vue3 related content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue3 uses axios interceptor to print front-end logs
  • Detailed example of using typescript to encapsulate axios in Vue3
  • Vue3 (V) Details of integrating HTTP library axios
  • Vue3 configures axios cross-domain implementation process analysis

<<:  Implementation of CSS sticky footer classic layout

>>:  The ultimate solution for playing background music in Firefox browser (Chrome multi-browser compatible)

Recommend

Vue implements dynamic circular percentage progress bar

Recently, when developing a small program, I enco...

How to regularly clean up docker private server images

Using CI to build docker images for release has g...

How to install Docker CE on Ubuntu 18.04 (Community Edition)

Uninstall old versions If you have installed an o...

A brief understanding of the differences between MySQL InnoDB and MyISAM

Preface MySQL supports many types of tables (i.e....

React mouse multi-selection function configuration method

Generally, lists have selection functions, and si...

Detailed explanation of how to restore database data through MySQL binary log

Website administrators often accidentally delete ...

Steps to split and compress CSS with webpack and import it with link

Let's take a look at the code file structure ...

MySQL 5.7.23 decompression version installation tutorial with pictures and text

Download the MySQL installer Official download ad...

MySQL 4 methods to import data

1. Import mysql command The mysql command import ...

A detailed introduction to JavaScript execution mechanism

Table of contents 1. The concept of process and t...

Introduction to the use of MySQL source command

Table of contents Thoughts triggered by an online...

MySQL installation and configuration methods and precautions under Windows platform

2.1、msi installation package 2.1.1、Installation I...

Detailed explanation of filters and directives in Vue

Table of contents vue custom directive Global Dir...

4 ways to modify MySQL root password (summary)

Method 1: Use the SET PASSWORD command First log ...

Detailed explanation of the execution process of JavaScript engine V8

Table of contents 1. V8 Source 2. V8 Service Targ...