微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

2022/05/27: VUE配置代理

通常VUE在进行跨域网络请求的时候需要用到配置代理

  • 请求的url中的“协议”、“域名”、“端口号”其中任何一种不一样都是属于跨域
  • 解决跨域的主要四种方法——jsonp、跨域资源共享CORS(Cross-Origin Resource Sharing)、proxy代理、webpack中间件

没有配置代理直接进行网络请求

<template>
  <div>
    <button @click="getStudents">获取学生信息</button>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'App',
  components: {  },
  methods:{
    getStudents() {
      axios.get("http://localhost:5000/students").then(
        response => {
          console.log('请求成功了', response.data)
        },
        error => {
          console.log('请求失败了', error.message)
        }
      )
    }
  }
}
</script>

<style>
</style>

结果:请求失败

image-20220526012512208

这里主要讲用VUE脚手架代理的方式来解决跨域问题

方式一

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

module.exports = defineConfig({
  devServer:{
    proxy:'http://localhost:5000'
  }
})

然后修改网络请求的端口号

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

修改了vue的配置后需要重新运行后才会生效,VUE首先会在前端请求资源,如果前端无该资源,会将请求转发给服务器(有限匹配前端资源)。

image-20220526085058349

这种方式的优缺点

  • 优点:配置简单,请求资源直接发给前端的端口号(8080),通过代理服务器请求(5000)
  • 缺点:不能配置多个代理,所有的请求最后都会走同一个代理(5000),并且不能灵活的控制请求是否走代理

方式二

在vue.config.js中添加具体的配置

module.exports = defineConfig({
  devServer:{
    proxy: {
      '/jiangwang': {
        target: 'http://localhost:5000',
        pathRewrite:{'^/jiangwang':''}, // 将/jiangwang替换为空
        ws:true,	// 开启webSocket
        changeOrigin:true	// false的时候后端用 request.getHeader("Host") 打印host是8080端口,开启后获取的host是5000端口
      },
      '/demo': {
        target: 'http://localhost:5001',
        pathRewrite:{'^/demo':''},
        ws:true,
        changeOrigin:true
      }
    }
  }
})

在VUE中修改请求

<template>
  <div>
    <button @click="getStudents">获取学生信息</button>
    <button @click="getCars">获取汽车信息</button>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'App',
  components: {  },
  methods:{
    getStudents() {
      axios.get("http://localhost:8080/jiangwang/students").then(
        response => {
          console.log('请求成功了', response.data)
        },
        error => {
          console.log('请求失败了', error.message)
        }
      )
    },
    getCars() {
      axios.get("http://localhost:8080/demo/cars").then(
        response => {
          console.log('请求成功了', response.data)
        },
        error => {
          console.log('请求失败了', error.message)
        }
      )
    }
  }
}
</script>

<style>
</style>

请求结果:

image-20220527001546485

方式二说明

  • 通过去对请求地址进行匹配,对匹配成功进行对于的代理,并且i需改原始请求
  • 优点:可以配置多个代理,并且可以灵活的控制请求是否走代理
  • 缺点:配置较为繁琐,在对应的请求需要加上前缀

原文地址:https://www.cnblogs.com/jiangblog/p/16315995.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐