vue2.X使用axios的get,post方法跨域问题

一.安装axios,并配置相应文件。这里跨域请求的接口来知乎的api

  安装 npm install axios --save

  使用及相关配置:

 1.在要使用axios的文件中引入

    import axios from 'axios';

  或者在src/main.js中全局声明

 import axios from 'axios';

 Vue.prototype.$axios=axios;

2.在 config/index.js 中的 的dev 添加以下代码,设置一下proxyTable

  proxyTable: {

      '/api': {

              target: 'https://news-at.zhihu.com/', //目标接口域名

             changeOrigin: true, //是否跨域

            pathRewrite: {

            '^/api': '/' //重写接口 ,这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替。比如我要调用''https://news-at.zhihu.com/api/4/news/latest',直接写‘/api/api/4/news/latest’即可

          }

     }

},

3、在 config/dev.env.js 中设置以下代码

         module.exports = merge(prodEnv, {

                 NODE_ENV: '"development"',  //开发环境

                API_HOST:"/api"

         })

4、在 config/prod.env.js 中设置以下代码

    module.exports = {

         NODE_ENV: '"production"',  //生产环境

         API_HOST:"https://news-at.zhihu.com/"

    }

5.然后xx.vue文件中就可以直接使用axios来进行跨域请求

  mounted(){

    axios.get('/api/api/4/news/latest')

   .then((res)=>{    //此时若不是jian箭头函数this将gaib改变的不是data中的数据

            console.log(res)

             console.log(this)

           if(res.status==200){

                       this.hotStory = res.data.top_stories;

                      this.allStory=res.data.stories;

              }

      }).catch((error)=>{

          console.log(error)

      })

}

6.以上配置完成后需要重新启动一下项目哦!

7.还有一种比较粗暴的方法,直接在浏览器中安装Allow-Control-Allow-Origin插件来解决跨域问题

直接在应用商店安装比较方便(但是需要翻墙,shadowsocks-win-dotnet4.0-2.3翻墙工具超级好用)如下图我安装的xian相关插件

8.如果跨域问题解决了,访问中仍存在403错误(及服务器拒绝访问时)需要在初始页面头部加入

<meta name="referrer" content='never' >跨域请求时不让其追踪到我们的请求

发布了45 篇原创文章 · 获赞 20 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/czp555/article/details/89303468