使用 npm:vue
$ npm install axios
或者 使用 bower:webpack
$ bower install axios
或者直接使用 cdn:ios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
main.js設置以下web
引入axiosnpm
import axios from 'axios'
掛載到vue的原型axios
Vue.prototype.$http = axios
在webpack.config.js(config—>index.js)文件裏設置代理 注意 新版文件會有修改api
dev: { env: require('./dev.env'), port: 8080, //設置訪問的端口號 autoOpenBrowser: true, //自動打開瀏覽器 assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api': { target: 'http://10.10:8063', //設置調用接口域名和端口號別忘了加http changeOrigin: true, pathRewrite: { '^/api': '/' //這裏理解成用‘/api’代替target裏面的地址,組件中咱們調接口時直接用/api代替 // 好比我要調用'http://0.0:300/user/add',直接寫‘/api/user/add’便可 代理後地址欄顯示/ } } }
// 爲給定 ID 的 user 建立請求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 可選地,上面的請求能夠這樣作 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // 兩個請求如今都執行完成 }));
建立實例
能夠使用自定義配置新建一個 axios 實例
axios.create([config])瀏覽器
var instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });