发新话题
打印

Vue之Axios跨域问题解决方案(已验证)

Vue之Axios跨域问题解决方案(已验证)

背景:因为axios中只能使用get和post方法来进行请求数据,没有提供jsonp等方法进行跨域访问数据
// axios 中的GET请求
axios.get('/user', {
    params: {
      ID: ‘001’
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 
// axios 中的POST请求
axios.post('/user', {
    firstName: '1',
    lastName: '2'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
方案1:既然使用axios直接进行跨域访问不可行,我们就需要配置代理了。代理可以解决的原因:因为客户端请求服务端的数据是存在跨域问题的,而服务器和服务器之间可以相互请求数据,是没有跨域的概念(如果服务器没有设置禁止跨域的权限问题),也就是说,我们可以配置一个代理的服务器可以请求另一个服务器中的数据,然后把请求出来的数据返回到我们的代理服务器中,代理服务器再返回数据给我们的客户端,这样我们就可以实现跨域访问数据。

准备工作:安装所需中间件和插件等,比如axios,http-proxy-middleware等。

具体案例:这里以访问豆瓣Top250为例,直接访问如下:

  1. axios.get("http://api.douban.com/v2/movie/top250")
  2. .then(res=>{
  3. console.log(res)
  4. })
  5. .catch(err=>{
  6. console.log(err)
  7. })

  8. 当执行npm run dev时,控制台报错如下:跨域了。。。



1.配置BaseUrl 在main.js中,配置数据所在服务器的前缀(即固定部分),代码如下: // 项目入口,配置全局vue import Vue from 'vue' import VueRouter from './router/routes.js' import Store from './store/index.js' import './assets/less/index.less' import App from './App.vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-default/index.css' import axios from 'axios' Vue.prototype.$axios = axios axios.defaults.baseURL = '/api' //关键代码 Vue.config.productionTip = false Vue.use(ElementUI); new Vue({ router:VueRouter, store:Store, template:'<App/>', components: {App} }).$mount('#app') // 默认进入商品模块 // VueRouter.push({ path: '/home' }) 关键代码:axios.defaults.baseURL = '/api',作用是我们每次发送的请求都会带一个/api的前缀。 2.配置代理 在config文件夹下的index.js文件中的proxyTable字段中,作如下处理: dev: { env: require('./dev.env'), port: 8090, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api': { target:'http://api.douban.com/v2', // 你请求的第三方接口 changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题 pathRewrite:{ // 路径重写, '^/api': '' // 替换target中的请求地址,也就是说以后你在请求http://api.douban.com/v2/XXXXX这个地址的时候直接写成/api即可。 } } }, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } 3.在具体使用axios的地方,修改url如下即可: axios.get("/movie/top250").then((res) => { res = res.data if (res.errno === ERR_OK) { this.themeList=res.data; } }).catch((error) => { console.warn(error) }) 4.重新启动项目之后,已经解决了跨域问题。
[ 本帖最后由 xiexie 于 2020-5-15 16:46 编辑 ]

TOP

发新话题