美文网首页Web前端之路
vue项目中axios的使用及跨域问题解决

vue项目中axios的使用及跨域问题解决

作者: 小西瓜Ly | 来源:发表于2019-10-24 14:34 被阅读0次

    1.npm install axios 安装axios,在main.js中引入并将axios改写为Vue的属性

    import axios from 'axios'
    Vue.prototype.$axios = axios
    Vue.prototype.HOME='https://xxxx.xxx.com'  // 发布正式或者测试版本不需要跨域,直接调用url即可
    // Vue.prototype.HOME = '/api' // this.HOME 本地调试
    

    2.找到config/index.js中的proxyTable配置代理来实现跨域请求

    proxyTable:{
        '/api':{
          target:"https://xxxx.xxx.com", // 接口域名
          changeOrigin:true,
          pathRewrite:{
            '^/api':""
          }
        }
     }
    

    3.在页面中this.axios调用即可

    // post
    this.$axios.post('/api/login',requestBody).then(res=>{
        console.log(res);
    },err=>{
        console.log(err);
    })
    // get
    let url = this.HOME + '/api/login'
    let data = this.$axios.get(url, {
      params: {
        name:name,  // get的参数写在params中
        pwd:pwd
      }
    })
    

    相关文章

      网友评论

        本文标题:vue项目中axios的使用及跨域问题解决

        本文链接:https://www.haomeiwen.com/subject/rearvctx.html