生成一个vue项目之后,开始写请求,请求数据,渲染到前端界面,有时候直接请求服务器上的接口,会遇到跨域问题,遇到跨域的时候,需要设置跨域代理~

1:进入新建的项目之中,使用npm安装axios模块。

   npm install axios --save
 
axios请求,跨域问题,设置跨域代理_分享
 

2:准备json数据
自己写了一个json数据,放在服务器上,现在要通过vue项目调用数据
http://www.intmote.com/test.json

3:跨域问题,设置代理,利用proxyTable属性实现跨域请求
在config/index.js 里面找到proxyTable :{} ,然后在里面加入以下代码

   proxyTable: {
  '/api': {
    target: 'http://www.intmote.com',//设置你调用的接口域名和端口号 别忘了加http
    changeOrigin: true,//允许跨域
    pathRewrite: {
      '^/api': '' //这个是定义要访问的路径,名字随便写 
    }
  }
},
 
axios请求,跨域问题,设置跨域代理_分享_02
 

4:打开一个界面test.vue,开始写请求数据的方法
在写代码之前,要记得引入import axios from 'axios'模块。

 methods: {
            getData() {
                axios.get('/api/test.json').then(response => {
                    console.log(response.data);
                }, response => {
                    console.log("error");
                });
            }
        }

test.vue参考代码:

<template>
  <div id='app'> axios请求数据</div>
</template>
<script>
import axios from 'axios'
export default {
  name: 'app',
  data () {
    return {
      itemList: []
    }
  },
  mounted () {
    this.getData()
  },
  methods: {
    getData () {
      axios.get('/api/test.json').then(
        response => {
          console.log(response.data)
        },
        response => {
          console.log('error')
        }
      )
    }
  }
}
</script>

6:再次运行
ctrl+c退出,再次使用命令启动npm run dev
这个时候,我们可以看见,请求的数据,返回值如下

 
axios请求,跨域问题,设置跨域代理_分享_03
 

 

打开network网络请求,可以看见请求已经代理完成~
http://localhost:8080/api/test.json

 
axios请求,跨域问题,设置跨域代理_分享_04
 

 
axios请求,跨域问题,设置跨域代理_分享_05
 

 

axios请求,跨域问题,设置跨域代理_分享_06