The main purpose of this article is to tell the students around me, who are learning or preparing to learn VUe3, how to use the network request AXIos in VUe3, in case the students who touch a little vue3 will have a question. Life cycle, router, VUX usage have all changed, how has axios usage changed?
The little sister
Axios needs to be installed before you can use it.
yarn add axios
npm install axios
bower install axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy the code
The above four installation methods, depending on the project you create, choose your own method.
First, axiO must be used basically
Create a component and introduce it to Axios to test if it succeeds! 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'
})
})
}
}
Copy the code
OnMounted is a lifecycle hook function that calls the network request when the page is loaded. The Axios method does not set the network request mode. The default is a GET request.
The network 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.
A message is displayed indicating a cross-domain problem.
Ii. How to solve cross-domain problems?
Use the proxy proxy to solve this problem. Create a vue.config.js file and add the configuration:
module.exports={
devServer:{
proxy:{
'/api':{
target:'https://xxxxx.net',
changeOrigin:true,
pathRewrite:{
'^/api':''
}
}
}
}
}
Copy the code
404 can’t find the address.
In vue2, the request is normal, but in VUe3 it is 404.
At the network request, add global configuration and remove the domain name from the URL at the request.
axios.defaults.baseURL ='/api'
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios({
url:'/hj/mp/banner/l'
})
Copy the code
When the modification is complete, the network request to refresh the page becomes successful.
Three, encapsulation
Without a tripartite library, the most is how to package, package after how to use, direct use not sweet?
Very clearly tell you, or too young…. Eat a few times and remember. The biggest advantage of encapsulation is that if there are bugs in the tripartite framework or you need to change the tripartite framework, you only need to change one place to complete the modification, easy maintenance, small workload, and not easy to miss.
Because axios requests many methods, there can be many 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'){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, Then (res=>{resolve(res)}). Catch (err=>{reject(err)})})} import {request} from '.. /network/request.js' export default { mounted(){ request('/hj/mp/banner/l').then(res=>{ console.log(res); }).catch(err=>{ console.log(err); }}})Copy the code
Since the Axios return is itself a Promise object, encapsulation is made easier by not instantiating the outer promise object.
Method 2:
BaseURL = "/ API "axios.defaults.timeout = 5000 export function request(config){ const instace = axios.create({ timeout:50000, Method: "post"}) / / request interceptor instace interceptors. Request. Use (config = > {return config}, err = > {}) / / response to intercept Instace. Interceptors. Response. Use (res = > {return res. Data}, err = > {/ / error handling}) return instace (config)} / / calls when using import {request} from './request' request({ url:'/hj/mp/banner/l', }).then(res=>{ console.log(res); }).catch(err=>{ console.log(err); })Copy the code
There are many ways to encapsulate Axios. If you are interested, you can go to the Axios document and try to encapsulate one by yourself, or save it for your own use. You don’t have to work hard to encapsulate it.
Global reference to Axios
The request method wrapped above can be referenced globally so that it can be used in any file in the project.
Add global properties to main.js
const app = createApp(App)
app.config.globalProperties.$http = request
app.mount('#app')
Copy the code
The order of the above three can not 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); })})}})Copy the code
Congratulations at the end, that’s the only thing that’s changed with Axios in Vue3.