vue2.0前端跨域方法笔记

360 阅读1分钟

方法一

使用JSONP

安装方法:

npm i -S vue-jsonp

导入

在main.js中引用vue-jsonp

import VueJsonp from 'vue-jsonp'
Vue.use(VueJsonp)

接下来就可以使用啦

 this.$jsonp('https://api.douban.com/v2/book/1220562',
 //豆瓣api
 {
     //请求参数
 } ).then(json => {
     console.log(json)
     //返回json
    }).catch(err => {
     console.log(err)
    })

方法二

配置

那么如果不使用JSONP,而是使用axios呢?

找到目录下config文件夹下的index.js

并添加以下代码

 proxyTable: {
      '/api': {
        target: 'https://api.douban.com/',
        //豆瓣api
        changeOrigin:true,
        pathRewrite: {  
          '^/api': ''  
        }
      }

使用

this.$axios
      .post("api/v2/book/1220562", {
      //打包之前修改为 .post("https://api.douban.com/v2/book/1220562",
      {
        //请求参数
      })
      .then(function(response) {
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });