Installing Axios in the project
CNPM Install Axios-s
Each component that needs to be requested needs to be introduced into the Axios, and if it is troublesome, it can be axios rewritten as the prototype property of Vue, and when used, it does not need to be referenced by each component.
To rewrite Axios into Vue's prototype properties
1. Introduction of Axios in Main.js
Import Axios from ' Axios '
2. The prototype attribute of Vue is written
Vue.prototype. $ajax = Axios
After adding these two lines of code in Main.js, you can use Axios directly in the component.
How to use
this. $ajax. Post (Url,params). Then (function (response) {
Request succeeded
}). catch (function (error) {
Request failed
});
Practical application
Suppose the interface we need to request is: Http://120.76.85.19:97/fx_ucs/services/local/users/[email protected]
If it is a development environment, the interface we request needs to be configured if there are cross-domain issues
There is a parameter called proxytable in the index.js in the VUE-CLI config file.
When configuring Proxytable, the local virtual server will receive your request and send it on your behalf, so there will be no cross-domain issues, of course, this applies only to the development environment.
Specific configuration code:
Configure agents
Proxytable: {
'/apis ': alias of {//'/apis '
Target: ' http://120.76.85.19:97 ',//target refers to the URL to proxy
Changeorigin:true,//whether cross-domain
pathrewrite:{
' ^/apis ': '//need rewrite rewrite
}
}
}
The specific code requested in the component:
this. $ajax. Post ('/apis/fx_ucs/services/local/users/[email protected] ', Qs.stringify ({
JobName: ' Getsiteproductanalysis ',
Datetype:this. Datetype
}). Then (function (response) {
Console.log (response)
}). catch (function (error) {
Console.log (Error);
});
Attention
Using Axios in Vue2, the parameters we requested are still JSON type and are not serialized. We need to use QueryString to solve the problem
Need to first introduce the import qs from ' QS ';
When passing in the parameter, the format is turned down,Qs. Stringify(data)
In this way, we are able to request access to the data normally.
In the build environment, the production code should use NPM run build and then put the dist on the Nginx server and configure the proxy address on Nginx.
Vue2 Project uses Axios to send requests