Standard VUE-CLI Project structure (Httpconfig folder built by itself):
Api.js:
// Const APIURL = ' http://test ';//test the domain name and change it to your own
Const APIURL = ' Http://xxoo '; // online domain name, you change to your own
default Apiurl
Http.js:
/** * Ajax Request Configuration*/Import Axios from' Axios 'Import Apiurl from'./api.js '//import qs from ' QS 'Import Cookie from‘.. /.. /static/js/cookie.js '//Axios Default ConfigurationAxios.defaults.timeout = 10000;//Timeout periodAxios.defaults.baseURL = Apiurl;//Default Address//Organize your dataAxios.defaults.transformRequest =function(data) {//data = qs.stringify (data);data =json.stringify (data); returndata;};//Routing Request Interception//http request Blockeraxios.interceptors.request.use (config= { //config.data = json.stringify (Config.data); config.headers[' content-type '] = ' application/json;charset=utf-8 '; //determine if there is a ticket, and if so, each HTTP header is added ticket if(Cookie.get ("token")) { //each time the user operates, the cookie is set to 2 hoursCookie.set ("token", Cookie.get ("token"), 1/12) cookie.set ("name", Cookie.get ("name"), 1/12)
Config.headers.token = Cookie.get ("token");
Config.headers.name= cookie.get ("name");
} returnconfig; }, Error= { returnPromise.reject (Error.response); });//Routing response Interception//HTTP Response InterceptorAxios.interceptors.response.use (Response= { if(response.data.resultcode== "404") {Console.log ("Response.data.resultCode is 404") //return error code-1 clear ticket information and jump to login page//Cookie.del ("Ticket")//window.location.href= ' http://login.com ' return }Else{ returnresponse; }}, Error= { returnPromise.reject (Error.response)//returns the error message returned by the interface}); exportdefaultAxios
Main.js
Import Axios from './httpconfig/http '= Axios
Sample Request:
Post
this. $http. Post ('/itemprops/additemprops 'the. Name, ParentID:this. ParentID, SortOrder:0}). Then (res)={
Console.log (RES)}). Catch (err) ={ alert ("request Failed")})
Get
this. $http. Get ("/roles/getpersonnelinforoles", {
params:{
Key: "Value"
}
}). Then (res) + = {
Console.log (RES)
}). catch ((Err) =>{
Alert ("Request Failed")
})
The global configuration of the Vue project to Axios