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

HTML+CSS+JavaScript to create a simple tic-tac-toe game

Table of contents Implementing HTML Add CSS Imple...

Why is it not recommended to use index as the key attribute value in Vue?

Table of contents Preface The role of key The rol...

Examples of vertical grid and progressive line spacing

New Questions Come and go in a hurry. It has been...

React-Native environment setup and basic introduction

Environment Preparation 1. Environment Constructi...

Introduction to cloud native technology kubernetes (K8S)

Table of contents 01 What is Kubernetes? 02 The d...

How to install mysql via yum on centos7

1. Check whether MySQL is installed yum list inst...

JavaScript anti-shake case study

principle The principle of anti-shake is: you can...

Analysis and solution of Chinese garbled characters in HTML hyperlinks

A hyperlink URL in Vm needs to be concatenated wit...

CentOS 6 uses Docker to deploy Zookeeper operation example

This article describes how to use docker to deplo...

User Experience Summary

Nowadays, whether you are working on software or w...

JS realizes automatic playback of timeline

Recently, I have implemented such an effect: clic...

CSS3 realizes various graphic effects of small arrows

It’s great to use CSS to realize various graphics...

Summary of some common techniques in front-end development

1. How to display the date on the right in the art...