vue项目中引入axios及使用

vue项目中引入axios及使用

一,下载依赖

$ npm install axios --save

二,引入依赖并全局注册

import axios from ‘axios’
Vue.prototype.$axios = axios

//全局注册,使用方法为:this.$axios

三,配置config文件

(1) ,通过webpack初始化的项目
在config文件夹中的index.js文件内修改如下:

dev: {
    env: require('./dev.env'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
            target: 'http://localhost:3000/api/',
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
            }
        }
    },
    host: '192.168.3.xxx',//IP地址
    port: 8080,
    autoOpenBrowser: true,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false,
    cacheBusting: true,
    cssSourceMap: false
}

(2) ,通过webpack-simple初始化的项目
在根目录下webpack.config.js文件中修改如下:

devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true,
    host: "192.168.3.xxx",//端口号
    port: 8080,
    proxy: {
      '/api/*': {
        target: 'http://localhost:3000',//跨域要访问的地址及端口
        changeOrigin: true,
        secure: false,
      }
    }
  }

四,使用并发送get请求

//以下代码也可以封装在函数中,在其他地方调用
this.$axios.get('/api/fillePath/apiPort', {
    params: {
      ID: 12345 //可选
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

五,使用并发送post请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

参考链接:
https://www.cnblogs.com/silent007/p/8603367.html
https://github.com/axios/axios

  • 19
    点赞
  • 102
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值