Vue2--Vue中配置代理服务器

11,917 阅读3分钟

配置代理服务器介绍

跨域问题

1、什么是跨域问题?

浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都会导致跨域问题。即前端接口去调用不在同一个域内的后端服务器而产生的问题。

2、如何解决跨域问题? --- 代理服务器

代理服务器的主要思想是通过建立一个端口号和前端相同的代理服务器进行中转,从而解决跨域问题。因为代理服务器与前端处于同一个域中,不会产生跨域问题;而且代理服务器与服务器之间的通信是后端之间的通信,不会产生跨域问题。

具体流程如下图所示,红色框代表浏览器,粉色框代表代理服务器,蓝色框代表后端的服务器。

image.png

3、如何实现代理服务器?-- 用vue-cli来实现

vue-cli配置官方文档

vue-cli配置代理的两种方法

方法一:在Vue.config.js中添加如下配置:

devServer:{
    proxy:"http://localhost:5000"
}

说明:

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

2、缺点:不能配置多个代理,不能灵活的控制请求是否走代理

3、工作方式:若按照上述配置代理,当请求了不存在的资源时,那么该请求就会转发给服务器(有限匹配前端资源)

方法二:编写vue.config.js配置具体代理规则

module.exports = {
    devServer: {
        proxy: {
            '/api1': { // 匹配所有以'/api1' 开头的请求路径
                target: 'http://localhost:5000', // 代理目标的基础路径
                changeOrigin: true,
                pathRewrite: {'^/api1':''}
            },
            '/api2': { // 匹配所有以'/api2' 开头的请求路径
                target: 'http://localhost:5001',// 代理目标的基础路径
                changeOrigin: true,
                pathRewrite: {'^/api2':''}
            },
        }
    }
}

/*
    changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
    changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
    changeOrigin默认值为true
*/

说明:

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

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

案例准备

1、服务器文件

说明:主要包含server1.js,server2.js文件

链接:pan.baidu.com/s/1t4uvyPdI…

提取码:euny

2、安装axios

npm i axios

案例一:

1、需求:使用axios接收server1.js的服务

2、实现:

App.vue

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

<script>
        import axios from 'axios'
	export default {
		name:'App',
		methods:{
			getStudents(){
				//注意:开启代理服务器后,get中的端口号要改为前端所在的端口号,即8080
				axios.get('http://localhost:8080/students').then(
					response => {
						console.log('请求成功了',response.data)
					},
					error => {
						console.log('请求失败了',error.message)
					}
				)
			},
		},
	}
</script>

vue.config.js(这里要先关闭vue,写完后在重启,不然配置更改不会生效)

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  // 关闭语法检查
  lintOnSave: false,
  // 开启代理服务器,注意:这里的端口号写后端的端口号(方式一)
  devServer: {
    proxy: 'http://localhost:5000'
  },
})

3、效果:

image.png

点击按钮后控制台输出

image.png

案例二:

1、需求:使用axios接收server1.js和server2.js的服务

2、实现:

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

<script>
        import axios from 'axios'
	export default {
		name:'App',
		methods:{
			getStudents(){
				//注意:采用了写法二,要加上前缀 /atguigu
				axios.get('http://localhost:8080/atguigu/students').then(
					response => {
						console.log('请求成功了',response.data)
					},
					error => {
						console.log('请求失败了',error.message)
					}
				)
			},
			getCars(){
				//注意:采用了写法二,要加上前缀 /demo
				axios.get('http://localhost:8080/demo/cars').then(
					response => {
						console.log('请求成功了',response.data)
					},
					error => {
						console.log('请求失败了',error.message)
					}
				)
			},
		},
	}
</script>

  • vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  // 关闭语法检查
  lintOnSave: false,
  // 开启代理服务器,注意:这里的端口号写后端的端口号(方式一)
  // devServer: {
  //   proxy: 'http://localhost:5000'
  // },

  // 开启代理服务器(方式二)
  devServer: {
    proxy: {
      // /atguigu 是请求的前缀
      '/atguigu': {
        target: 'http://localhost:5000',
        //重写路径,把所有路径中包含/atguigu的路径替换为空字符串
        pathRewrite: {'^/atguigu':''}, 
        // 用于支持websocket
        ws: true,
        // 用于控制请求头中的host值
        changeOrigin: true
      },
      '/demo': {
        target: 'http://localhost:5001',
        //重写路径,把所有路径中包含/atguigu的路径替换为空字符串
        pathRewrite: {'^/demo':''}, 
        // 用于支持websocket
        ws: true,
        // 用于控制请求头中的host值
        changeOrigin: true
      },
    }
  }
})

3、效果:

  • 网页显示:

image.png

  • 控制台输出:

image.png