Vue安裝axios實現接口請求


一、vue-cli使用aios

    1、安裝命令:cnpm instal  axios --save

    2、main.js引入全局使用

//axios import axios from 'axios' Vue.prototype.$axios = axios

        3、組件或頁面中使用

 methods: 
      {
        testAxios1:function(){ console.log('test'); this.$axios({ method: 'get', url: 'data/personData.json' }) .then(function (response) { console.log(response) }) .catch(function (error) { console.log(error) }) },

二、axios配置開發環境跨域請求代理

1:打開config/index.js

在這里面找到proxyTable{},改為這樣:

  proxyTable: { '/api': { target: 'http://localhost:8085',//設置你調用的接口域名和端口號 別忘了加http changeOrigin: true, pathRewrite: { '^/api': ''//這里理解成用‘/api’代替target里面的地址,后面組件中我們掉接口時直接用api代替 比如我要調用'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add’即可 } } },

2、使用

 methods: 
      {
        testAxios1:function(){ console.log('test'); this.$axios({ method: 'post', url: 'http://localhost:8085/screen/selCaugh' }) .then(function (response) { console.log(response) }) .catch(function (error) { console.log(error) }) },

 

 

三、axios傳參

1:Vue官方推薦組件axios默認就是提交 JSON 字符串,所以我們要以json字符串直接拼接在url后面的形式,直接將json對象傳進去就行了

let postData = {
  companyCode:'tur',
  userName:'123456789123456789',
  password:'123456'
}
axios.get('/api/yt_api/login/doLogin',{
  params: {
    ...postData,
  }
})
.then(function (response) {
  console.log(1)
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});


免責聲明!

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



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