Axios -- Ajax请求

基础用法

易用、简洁且高效的http库: http://www.axios-js.com/docs/ 

$ npm install axios -s #安装

整合Vue-cli脚手架: 在 main.js 文件中添加如下信息:

import axios from 'axios'
//将axios挂载在Vue扩展上 , 在其他地方使用只需使用 this.$http来代替axios; 
Vue.prototype.$http = axios
//配置baseUrl,所有的 axios 请求地址都会加上 /api
axios.defaults.baseURL = '/api'

官方 API 案例:

// 发送 POST 请求
axios({
    method: 'post',
    url: '/user/12345', 
   data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
    }
 });
// 为给定 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); 
});

跨越请求配置

参考配置地址:https://cli.vuejs.org/zh/config/#devserver-proxy

如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服 务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。

vue.config.js 是一个可选的配置文件,如果项目的 (和 package.json 同级的) 根目录中存在这个文件,那 么它会被 @vue/cli-service 自动加载。这个文件应该导出一个包含了选项的对象:

module.exports = { 
    publicPath: '',
    devServer: {  
    /**
    * 这里的设置会把 /api 开头的请求代理到 http://localhost:9001 中去
    * 比如请求地址: '/api/test02'
    * 在没有配置pathRewrite的情况下实际真正的请求地址是:'http://localhost:9001/api/test02'
    * 如果配置了 pathRewrite {'^/api': ''}  请求/student/list
    * 那么后的真正的请求地址就会变为:'http://localhost:9001/api/student/list'
    * */
        port: 80,
        proxy: {   
            '/api': {
                //代理以 api 开头的请求        
                target: 'http://127.0.0.1:80/',
                //当前请求地址代理到配置的目标地址上 
                ws: true,
                changeOrigin: true, //是否开启跨域
                pathRewrite: {      
                    '^/api': '' //规定请求地址以什么作为开头 
                } 
            } 
        }
    }
}

案例演示:

//生成的请求地址:http://localhost:8080/api/student/list -->代理转发会省去/api 
this.$http.get('/student/list').then(function(res){
   console.log(res); })

 this.$http.get('/student/list')

  .then(res => {
    console.log(res.data.data)
    this.tableData = res.data.data
  })
}

原文地址:https://www.cnblogs.com/chahune/p/13219564.html