標籤:ram ack 自訂 open 自動 tab 一個 調用介面 pkg
安裝
使用 npm:
$ npm install axios
或者 使用 bower:
$ bower install axios
或者直接使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
main.js設定如下
引入axios
import axios from ‘axios‘
掛載到vue的原型
Vue.prototype.$http = axios
在webpack.config.js(config—>index.js)檔案裡設定代理 注意 新版檔案會有修改
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‘}});
axios的詳細用法以及後端介面代理