Vue.js Ajax

1.封裝AJAX模塊

(1)在src目錄下新建api目錄,新建ajax.js,寫入
(2)引入axios
(3)定義ajax函數,並暴漏出去
(4)ajax函數中調用axios發送請求,並將返回的promise對象 return出去vue

// 引入axios
import axios from 'axios'

// 暴露ajax
// ajax接收3個參數:url,參數,請求方法
export default function ajax (url='',data={},type='get') {
    let promise
    if(type.toLowerCase() === 'get'){
        //若是是get請求,則將參數拼接到url後面
        let dataStr = ''
        Object.keys(data).forEach(key => {
            // key=value&
            dataStr += key + '=' +data[key] + '&'
        })
        if(dataStr !== ''){
            // 去除最後一個&
            dataStr = dataStr.substring(0,dataStr.lastIndexOf('&'))
            // 將參數拼接到url後面
            url = url + '?' + dataStr
        }
        // 發送get請求,返回一個promise對象
        promise = axios.get(url)
    }else {
        // 發送post請求,返回一個promise對象
        promise = axios.post(url,data)
    }
    // 將promise返回
    return promise
}

(5)引入該模塊並使用ios

// App.vue
<script>
import ajax from './api/ajax.js'

export default {
  mounted () {
    const url = 'https://api.github.com/search/repositories'
    ajax(url,{q:'vue',sort:'stars'}).then(res => {
      console.log(res.data.items[0])
    }).catch(error => {
        alert('請求失敗')
    })
  }
}
</script>

2.配置代理解決跨域問題

打開config/index.js文件,找到proxyTable屬性進行git

proxyTable: {
    '/api': {  // 匹配以/api開頭的全部路徑
        target: 'http://localhost:4000', // 代理的後端api基礎路徑
        changeOrigin: true, // 支持跨域
        pathRewrite: { // 重寫路徑,去掉路徑中開頭的'/api'
            '^/api': ''
            // '^/api': 'api' 
        }
    }
}

若是要訪問後臺api地址,例如:http://localhost:4000/Listgithub

axios.get('/api/List') // 會 自動替換成 http://localhost:4000/List

若是配置成這樣:ajax

pathRewrite: {
    '^/api': 'api'
}

訪問後臺地址就應該是 http://localhost:4000/api/Listaxios

相關文章
相關標籤/搜索