• vue跨域问题解决


    vue服务部署在 http://localhost:8081,后台服务部署在 http://localhost:8080,可以看到端口是不一样的,在vue通过以下方式请求:

     1 export default {
     2     name:'Condition',
     3     data(){
     4         return{
     5             options:[]
     6         }
     7     },
     8     created:function(){
     9         this.getdata();
    10     },
    11     methods:{
    12         getdata(){
    13             this.$axios({
    14                 method:'get',
    15                 url:'http://localhost:8080/college/getcollege'
    16                 }).then(resp => {
    17                     this.options = resp.data.data.list;
    18                     console.log(resp.data);       
    19                 }).catch(resp => {
    20                     console.log('请求失败:'+resp.status+','+resp.statusText);
    21                 });
    22         }
    23     }
    24 }
    View Code

    因为端口不一致,axios就会认为是跨域了,所以就会报错:

    这里只介绍通过修改config中的index.js文件中的proxyTable的配置去解决的方法。在网上随便搜一下,基本都是如下的内容:

    devServer: {
        port: port,
        open: true,
        overlay: {
          warnings: false,
          errors: true
        },
        // before: require('./mock/mock-server.js')
        proxy: {
          '/api': {  //使用"/api"来代替"http://admin.com"
            target: process.env.VUE_APP_BASE_API, //源地址
            secure: false,
            changeOrigin: true, //改变源
            pathRewrite: {
              '^/api': ''//路径重写
            }
          }
        },
      },
    

      

    修改后,绝大部分人都会遇到404的错误
    明明设置了代理,怎么没有生效呢?不是方法不对,而是没有理解proxyTable中节点的意义。
    其中的“api”节点,这是路由,系统会去根据这个匹配你的地址,匹配上才会生效,proxyTable中可以指定多个路由,
    一开始会认为这个是规定格式,所以都不会去修改,除非你的api部署地址是这样的“http://localhost:9001/api/*”,
    恭喜你,你的问题可能解决了,但是根据我的地址是“http://127.0.0.1:9001/admin/api”,就完蛋了,那么该怎么改,如下:

    proxy: {
          '/api': {  //使用"/api"来代替"http://admin.com"
            target: process.env.VUE_APP_BASE_API, //源地址
            secure: false,
            changeOrigin: true, //改变源
            pathRewrite: {
              '^/admin/api': '/admin/api'//路径重写
            }
          }
        },
    

      

    就ok了。

    两种方法部署

    1. 用java自带的index
      a. 把vue的dist目录下所有文件拷贝到java工程的resource/static/下面
      b. java编译打包,启动
      c. 访问web的admin/static/index.html

    2. python 起http服务
      a. 安装python2/3
      b. vue的 dist目录下,运行python -m SimpleHTTPServer 8008
      c. 访问本机 ip:端口/index.html

    博客园:https://www.cnblogs.com/xianquan
    Copyright ©2020 l-coil
    【转载文章务必保留出处和署名,谢谢!】
  • 相关阅读:
    读后感
    mysql分库分表的基本方法
    pdo接口用法
    视频技术基础
    【原创】shell易错语法汇总
    php底层的运行机制
    mysql统计函数
    etc/shadow 登陆口令破解
    JAVA学习(方法重载)
    JAVA学习(方法的定义及调用)
  • 原文地址:https://www.cnblogs.com/xianquan/p/12748123.html
  • Copyright © 2020-2023  润新知