zoukankan      html  css  js  c++  java
  • vue.config.js解决跨域问题

    需求我们要访问后台的数据,但因为后台的端口号不一致所以需要实现跨域

    未跨域

    // 请求接口 后台的接口为5001 我们本地的接口为8080,所以我们需要去到vue.config.js配置跨域 http://localhost:5001/api/
      this.$axios.post('http://localhost:5001/api/users/register',this.user)
      .then(res =>{
        // 注册成功
        alert('注册成功!')
        this.$router.push('/login')
        console.log(res)
      })//在http全局配置了catch所以这边是不用配置的
    }

    在当前项目的根路径下新建一个文件,文件名是固定的 vue.config.js —>proxy

      module.exports = {
        devServer: {
          open: true,
          host: 'localhost',
          port: 8080,
          https: false,
          //以上的ip和端口是我们本机的;下面为需要跨域的
          proxy: {  //配置跨域
            '/api': {
              target: 'http://localhost:5001/api/',  //这里后台的地址模拟的;应该填写你们真实的后台接口
              ws: true,
              changOrigin: true,  //允许跨域
              pathRewrite: {
                '^/api': ''  //请求的时候使用这个api就可以
              }
          }
        }
      }
    }

    跨域页面使用:

        // 请求接口 后台的接口为5001 我们本地的接口为8080,所以我们需要去到vue.config.js配置跨域 http://localhost:5001/api/
        this.$axios.post('/api/users/register',this.user)
        .then(res =>{
          // 注册成功
          alert('注册成功!')
          this.$router.push('/login')
          console.log(res)
        })//在http全局配置了catch所以这边是不用配置的
      }

    跨域成功:

     

     hint:只要是修改了配置就一定要重启项目
    ————————————————
    原文链接:https://blog.csdn.net/qq_40190624/article/details/85257610

  • 相关阅读:
    我们毕业了!!!@全体成员
    华东交通大学编译原理期末试卷
    软件设计师中级下午答题解题策略分析~
    Java实现旅行商最短距离
    基于SSH的医院在线挂号
    基于Java的模拟写字板的设计与实现
    基于java的雷电游戏
    基于Java的飞机大战游戏的设计与实现
    基于Java的超级玛丽游戏的设计与实现
    基于Javaee的影视创作论坛的设计与实现
  • 原文地址:https://www.cnblogs.com/whoamimy/p/11945474.html
Copyright © 2011-2022 走看看