vue Axios跨域

第一步:修改main.js

import axios from 'axios'

Vue.prototype.$axios = axios

axios.defaults.baseURL = '/api'

  第二步:修改 config 下面的index.js文件

dev: {
    env: require('./dev.env'),
    open: true,
    host:'127.0.0.1',//本人测试 新增这些 不知道为什么 求大佬解释
    port: 8080,
    https: false,//同上
    hotOnly: false,//同上
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target:'http://test.com/', // 你请求的第三方接口
        ws:true,
        changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
        pathRewrite:{  // 路径重写,
          '^/api': ''  // 替换target中的请求地址
        }
      }
    },
    cssSourceMap: false
  }

  第三步,测试接口

mounted() {
    const url = "index.php";
    this.$axios.get(url).then(response => {
                    if (response.data) {
                        console.log(response.data)
                    }
                }).catch(err => {
                    alert('请求失败')
                })
                
  }

  

posted @ 2020-05-14 16:00  li阿根  阅读(245)  评论(0编辑  收藏  举报