vue使用axios、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’即可
        }
      }
    },

61665af5bb29ed540fcbfbbfaaa8ab86523.jpg

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);
});

转载于:https://my.oschina.net/u/3234821/blog/3046256

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值