通过Vue解决跨域问题(proxy配置代理)【转载】

当我们在用本机去找服务器要数据时会产生跨域问题,所以利用vue-cli去开启一个代理服务器。

方法一:

在vue.config.js中添加如下配置

//开启代理服务器(方式一)
   devServer: {
//请求服务器的地址
   proxy: 'http://localhost:5000'
  }

配置成功之后必须要重新启动脚手架,否则不会开启代理服务器

请求时:

axios.get("http://localhost:8081/students").then(
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );

优点:配置简单,当请求资源时直接发给前端(8080)即可

缺点:不能配置多个代理,只能配置一个代理服务器,不能灵活的控制请求是否走代理。

工作方式:按照上述配置代理,当请求资源不存在时,请求会转发给服务器(优先匹配前端资源)

方法二:

在vue.config.js中添加如下配置

//开启代理服务器(方法二)
    devServer: {
        proxy: {
            //  '/yu'为请求前缀,用于控制是不是走代理,想走代理时就在请求前缀前边加上这个请求前缀
            '/yu': {
                target: 'http://localhost:5000',
                pathRewrite: { "^/yu": "" }, //重写路径  匹配以/yu为开头的路径都变为空字符串 
                ws: true, //用于支持websocket
                changeOrigin: true //用于控制请求头中的host值
            },
            '/demo': {
                target: 'http://localhost:5001',
                pathRewrite: { "^/demo": "" },
                ws: true, //用于支持websocket
                changeOrigin: true //用于控制请求头中的host值
            },
        }
    }

请求时:

请求前缀必须跟着端口号

getStudents() {
      axios.get("http://localhost:8081/yu/students").then(
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },
    getCars() {
      axios.get("http://localhost:8081/demo/cars").then(
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },

优点:可以配置多个代理,灵活的控制请求是否走代理

缺点:配置略繁琐,请求资源时必须加前缀

 

posted @ 2023-02-14 17:38  ysx_小鱼  阅读(379)  评论(0编辑  收藏  举报