1.安裝axiosios
npm:npm
$ npm install axios -S
cdn:axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2.配置axios後端
在項目中新建api/index.js文件,用以配置axiosapi
api/index.js跨域
import axios from 'axios'; let http = axios.create({ baseURL: 'http://localhost:8080/', withCredentials: true, headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }, transformRequest: [function (data) { let newData = ''; for (let k in data) { if (data.hasOwnProperty(k) === true) { newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&'; } } return newData; }] }); function apiAxios(method, url, params, response) { http({ method: method, url: url, data: method === 'POST' || method === 'PUT' ? params : null, params: method === 'GET' || method === 'DELETE' ? params : null, }).then(function (res) { response(res); }).catch(function (err) { response(err); }) } export default { get: function (url, params, response) { return apiAxios('GET', url, params, response) }, post: function (url, params, response) { return apiAxios('POST', url, params, response) }, put: function (url, params, response) { return apiAxios('PUT', url, params, response) }, delete: function (url, params, response) { return apiAxios('DELETE', url, params, response) } }
這裏的配置了POST、GET、PUT、DELETE方法。而且自動將JSON格式數據轉爲URL拼接的方式app
同時配置了跨域,不須要的話將withCredentials設置爲false便可post
而且設置了默認頭部地址爲:http://localhost:8080/,這樣調用的時候只需寫訪問方法便可this
3.使用axiosurl
注:PUT請求默認會發送兩次請求,第一次預檢請求不含參數,因此後端不能對PUT請求地址作參數限制
首先在main.js中引入方法
import Api from './api/index.js';
Vue.prototype.$api = Api;
而後在須要的地方調用便可
this.$api.post('user/login.do(地址)', { "參數名": "參數值" }, response => { if (response.status >= 200 && response.status < 300) { console.log(response.data);\\請求成功,response爲成功信息參數 } else { console.log(response.message);\\請求失敗,response爲失敗信息 } });