The first step is to download the Axios first
CNPM Install Axios-s
The second step is to create a htttp.js
Import Axios from ' Axios ', import {Message} from ' Element-ui '; axios.defaults.timeout = 5000;axios.defaults.baseurl = '; /http Request Interceptor Axios.interceptors.request.use (config = {//Const token = GetCookie (' name '); note that when using the cookie method, push Recommended Js-cookie Config.data = json.stringify (Config.data); Config.headers = {' Content-type ': ' application/x-www-form-urlencoded '}//if (token) {//Config.params = { ' token ': token}//} return config; }, Error = {return Promise.reject (err); });//http Response Interceptor Axios.interceptors.response.use (response + = {if (Response.data.errCode ==2) {Router.pus H ({path: "/login", querry:{redirect:router.currentroute.fullpath}//from which page to jump})} return response; }, Error = {return Promise.reject (Error)})/** * Package Get method * @param URL * @param data * @returns {Promise} */expo RT function Fetch (url,params={}) {return new Promise ((resolve,reject) = {Axios.get (url,{params:params }). Then (response = {resolve (response.data); }). catch (Err = {reject (ERR)})})}/** * encapsulate POST request * @param URL * @param data * @returns {Promise} */Expo RT function Post (Url,data = {}) {return new Promise ((resolve,reject) = {axios.post (url,data). Then (res Ponse = {Resolve (response.data); },err = {reject (ERR)})}}/** * Package patch request * @param URL * @param data * @returns {Promise} */ Export function Patch (Url,data = {}) {return new Promise ((resolve,reject) = {Axios.patch (url,data). Then ( Response = {Resolve (response.data); },err = {reject (ERR)})}}/** * encapsulate put request * @param URL * @param data * @returns {Promise} */export function put (url,data = {}) {return new Promise ((resolve,reject) = {axios.put (url,data). Then (response = > {resolve (Response.data); },err = {reject (err) }) })}
Step Three
Introduced in the Main.js
Import Axios from ' Axios ' import {post,fetch,patch,put} from './utils/http '//define global variable Vue.prototype. $post =post; Vue.prototype. $fetch =fetch; Vue.prototype. $patch =patch; Vue.prototype. $put =put;
And then use it directly in the component.
Mounted () {This . $fetch ('/api/v2/movie/top250 ') and then ((response) = { Console.log (response) }) }, the rest of the methods are the same
The Axios package in Vue