vue中怎么解决跨域路由冲突问题

发布时间:2021-07-09 14:28:36 作者:Leah
来源:亿速云 阅读:129

今天就跟大家聊聊有关vue中怎么解决跨域路由冲突问题,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

vue 简介

Vue.js(读音 /vjuː/, 类似于 view) 是一套构建用户界面的渐进式框架。

Vue 只关注视图层, 采用自底向上增量开发的设计。

Vue 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。

Vue 学习起来非常简单,本教程基于 Vue 2.1.8 版本测试。

当我们在路由里面配置成以下代理可以解决跨域问题

proxyTable: {
   '/goods/*': {
    target: 'http://localhost:3000'
   },
   '/users/*': {
    target: 'http://localhost:3000'
   }
  },

这种配置方式在一定程度上解决了跨域问题,但是会带来一些问题,

比如我们的vue 路由 也命名为 goods,这时候就会产生了冲突,

如果项目中接口很多,都在这里配置是很麻烦的,也容易产生路由冲突。

正确的姿势

如果把所有的接口,统一规范为一个入口,在一定程度上会解决冲突

把以上配置统一前面加上 /api/

proxyTable: {
   '/api/**': {
    target: 'http://localhost:3000'
   },
  },

如果我们配置成这种方式,在使用http请求的时候就会发生变化,会在请求前面加上一个api,相对路由也会发生变化,也会在接口前面加上api,这样也会很麻烦,我们可以使用以下方式来解决这个问题

proxyTable: {
   '/api/**': {
    target: 'http://localhost:3000',
    pathRewrite:{
     '^/api':'/'
    }
   },
  },

上面这个代码,就是把咱们虚拟的这个api接口,去掉,此时真正去后端请求的时候,不会加上api这个前缀了,那么这样我们前台http请求的时候,还必须加上api前缀才能匹配到这个代理,代码如下:

logout(){
  axios.post('/api/users/logout').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 },
 getGoods(){
  axios.post('/api/goods/list').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 }

我们可以利用axios的baseUrl直接默认值是 api,这样我们每次访问的时候,自动补上这个api前缀,就不需要我们自己手工在每个接口上面写这个前缀了

在入口文件里面配置如下:

import Axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, Axios)
Axios.defaults.baseURL = 'api'

如果这配置 ‘api/' 会默认读取本地的域

上面这样配置的话,不会区分生产和开发环境

在config 文件夹里面新建一个 api.config.js 配置文件

const isPro = Object.is(process.env.NODE_ENV, 'production')
module.exports = {
 baseUrl: isPro ? 'http://www.vnshop.cn/api/' : 'api/'
}

然后在main.js 里面引入,这样可以保证动态的匹配生产和开发的定义前缀

import apiConfig from '../config/api.config'
import Axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, Axios)
Axios.defaults.baseURL = apiConfig.baseUrl

经过上面配置后,在dom里面可以这样轻松的访问,也不需要在任何组件里面引入axios模块了。

logout(){
  this.$http.post('/users/logout').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 },
 getGoods(){
  this.$http.post('/goods/list').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 }

最终代码

在代理里面配置

proxyTable: {
   '/api/**': {
    target: 'http://localhost:3000',
    pathRewrite:{
     '^/api':'/'
    }
   },
  },

在config里面的api.config.js 配置

在config 文件夹里面新建一个 api.config.js 配置文件

const isPro = Object.is(process.env.NODE_ENV, 'production')
module.exports = {
 baseUrl: isPro ? 'http://www.vnshop.cn/api/' : 'api/'
}

关于生产和开发配置不太了解

可以去 dev-server.js 里面看配置代码

const webpackConfig = (process.env.NODE_ENV === 'testing' || process.env.NODE_ENV === 'production') ?
 require('./webpack.prod.conf') :
 require('./webpack.dev.conf')

在main.js 入口文件里面配置

import apiConfig from '../config/api.config'
import Axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, Axios)
Axios.defaults.baseURL = apiConfig.baseUrl

在dom里面请求api的姿势

logout(){
  this.$http.post('/users/logout').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 },
 getGoods(){
  this.$http.post('/goods/list').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 }

PS:下面通过一段代码学习下vue下跨域设置

1、在使用vue开发的时候经常要涉及到跨域的问题,其实在vue cli中是有我们设置跨域请求的文件的。

2、当跨域无法请求的时候我们可以修改工程下config文件夹下的index.js中的dev:{}部分。

dev: {
  env: require('./dev.env'),
  port: 8080,
  autoOpenBrowser: false,
  assetsSubDirectory: 'static',
  assetsPublicPath: '/',
  proxyTable: {
    '/api': {
      target: 'http://api.douban.com/v2',
      changeOrigin: true,
      pathRewrite: {
        '^/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
}

将target设置为我们需要访问的域名。

3、然后在main.js中设置全局属性:

Vue.prototype.HOST = '/api'

4、至此,我们就可以在全局使用这个域名了,如下:

var url = this.HOST + '/movie/in_theaters'
  this.$http.get(url).then(res => {
   this.movieList = res.data.subjects;
  },res => {
   console.info('调用失败');
  });

看完上述内容,你们对vue中怎么解决跨域路由冲突问题有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. vue-cli3 中怎么解决跨域问题
  2. 利用vue怎么解决跨域问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue

上一篇:react.js如何实现批量添加与删除功能

下一篇:Vue如何实现数组更新及过滤排序功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》