axios的詳細用法以及后端接口代理


安裝


使用 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'}
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM