首页 > 其他分享 >Vue 配置代理服务器

Vue 配置代理服务器

时间:2023-03-08 14:13:48浏览次数:46  
标签:Vue http name age 配置 代理服务器 axios id

js发ajax请求的几种方式

- xhr(原生js自带): new XMLHttpRequest() xhr.open() xhr.send()

- jQuery: $.get() $.post

- axios(推荐)

- fetch(windows对象自带): 有致命缺陷...
  • 安装 axios

    num i axios
    
  • demo演示

    - 后端接口的地址: http://127.0.0.1:8888/demo/
    
    - 返回正常的数据是这样:
    	{
        "data": [
            {
                "id": 1,
                "name": "JimGreen",
                "age": 20
            },
            {
                "id": 2,
                "name": "KateGreen",
                "age": 18
            },
            {
                "id": 3,
                "name": "LiLei",
                "age": 20
            },
            {
                "id": 4,
                "name": "HanMeiMei",
                "age": 19
            }
        ]
    }
    
    
### Student.vue(一个按钮发送请求,控制台打印返回信息)
<template>
	<button type="button" @click="getStudentName">获取学生信息</button>
</template>

<script>
	import axios from 'axios'
	export default {
		name:'Student',
		methods:{
			getStudentName(){
				axios.get('http://127.0.0.1:8888/demo/').then(
					response => {console.log('请求成功',response.data)},
					error => {console.log('请求失败',error.message)}
				)
			}
		}
	}
</script>

<style>
</style>

- 结果: 由于浏览器的同源策略,跨域失败(服务器有收到请求,但是返回的数据被浏览器阻止了)

	- 前端运行的地址: http://localhost:8080/
	- 后端运行的地址: http://localhost:8000/demo/
	
	- 区别: 协议&&域名 都一样,但是端口不一样,所以不同源,被拒绝

	...been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

跨域的解决方案

- cors # 真正解决跨域问题(后端处理)

- jsonp: 利用 <script src>,只能发送get请求(前后端一起配合...)

- 代理服务器
  • 本次讲的就是使用'代理服务器'解决问题

  • 代理服务器

    - nginx
    
    - vue-cli: 架了一个和客户端 端口一样的服务器
    
  • vue-cli 代理服务器解决跨域问题

    ### vue.config.js(配置完,一定要重启脚手架服务器,否则不生效)
    const { defineConfig } = require('@vue/cli-service')
    module.exports = defineConfig({
      ......
      // 代理服务器
      devServer: {
    	  // 配置目标服务器地址
          proxy: 'http://localhost:8888'
        }
    })
    
    ### Student.vue
    <template>
    	<button type="button" @click="getStudentName">获取学生信息</button>
    </template>
    
    <script>
    	import axios from 'axios'
    	export default {
    		name:'Student',
    		methods:{
    			getStudentName(){
    				// 注意: 不再是向目标服务器发起请求
    				// 而是向本机的代理服务器发起请求+目标服务器的路径
    				axios.get('http://localhost:8080/demo/').then(
    					response => {console.log('请求成功',response.data)},
    					error => {console.log('请求失败',error.message)}
    				)
    			}
    		}
    	}
    </script>
    
    - 返回结果: 正常返回数据了
    
    	ata: Array(4)
        0: {id: 1, name: 'JimGreen', age: 20}
        1: {id: 2, name: 'KateGreen', age: 18}
        2: {id: 3, name: 'LiLei', age: 20}
        3: {id: 4, name: 'HanMeiMei', age: 19}
        length: 4
        
    - 注意事项: 若脚手架的代理服务器本身就有 demo路径的资源,那么请求会优先得到代理服务器的响应
      代理服务器不再进行转发
      
    - 这种配置方式的缺陷有两点
    
    	- 不能配置多个代理
    	- 代理服务器有的资源,就不再进行转发
    
    
  • 配置多个代理服务器演示

    - 后端接口的地址1: http://127.0.0.1:8888/demo/test1
    - 后端接口的地址2: http://127.0.0.1:8888/demo/test2
    
    - 地址1返回数据
    	{
        "data": [
            {
                "id": 1,
                "name": "JimGreen",
                "age": 20
            },
            {
                "id": 2,
                "name": "KateGreen",
                "age": 18
            },
            {
                "id": 3,
                "name": "LiLei",
                "age": 20
            },
            {
                "id": 4,
                "name": "HanMeiMei",
                "age": 19
            }
        ]
    }
    
    - 地址2返回数据
    
    {
        "data": [
            {
                "id": 1,
                "name": "安宁",
                "age": 20
            },
            {
                "id": 2,
                "name": "云帆",
                "age": 18
            },
            {
                "id": 3,
                "name": "东东",
                "age": 20
            },
            {
                "id": 4,
                "name": "林林",
                "age": 19
            }
        ]
    }
    
### vue.config.js
......
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  ......
  // 代理服务器
  // devServer: {
	 //  // 配置目标服务器地址
  //     proxy: 'http://localhost:8888'
  //   }
  
  devServer: {
	  proxy: {
		'/test1': { // 加前缀
		  target: 'http://localhost:8888', // 目标服务器地址
		  pathRewrite:{'^/test1':''} // 正则匹配,去掉这个前缀
		  // ws: true, // 用于支持 websocket
		  // changeOrigin: true // 用于控制请求头中的host值(是否隐藏客户端地址)
		},
		'/test2': {
		  target: 'http://localhost:8888',
		  pathRewrite:{'^/test2':''}
		 ......
		},
	  }
    }
  
})

### Student.vue
<template>
	<div>
		<button type="button" @click="getStudentName">获取学生信息</button>
		<button type="button" @click="getChineseName">获取中文信息</button>
	</div>
	
</template>

<script>
	import axios from 'axios'
	export default {
		name:'Student',
		methods:{
			getStudentName(){
				// axios.get('http://localhost:8080/demo/').then(
				// 代理服务器地址+目标服务器资源路径
				axios.get('http://localhost:8080/demo/test1/').then(
					response => {console.log('请求成功',response.data)},
					error => {console.log('请求失败',error.message)}
				)
			},
			getChineseName(){
				// axios.get('http://localhost:8080/demo/').then(
				axios.get('http://localhost:8080/demo/test2/').then(
					response => {console.log('请求成功',response.data)},
					error => {console.log('请求失败',error.message)}
				)
			},
			
		}
	}
</script>

<style>
</style>

vue脚手架配置代理

  • 方法一

    ### vue.config.js
    ......
    devServer: {
    	  // 配置目标服务器地址
          proxy: 'http://localhost:8888'
        }
    
    - 优点: 配置简单,请求资源时直接发给前端代理服务器即可
    - 缺点: 不能配置多个代理,不能灵活的控制请求是否走代理
    
  • 方法二

    ### vue.config.js
    ......
    devServer: {
    	  proxy: {
    		'/test1': { // 取个名字
    		  target: 'http://localhost:8888', // 目标服务器地址
    		  pathRewrite:{'^/test1':''} // 正则匹配,去掉这个名字
    		  // ws: true, // 用于支持 websocket
    		  // changeOrigin: true // 用于控制请求头中的host值(是否隐藏客户端地址)
    		},
    		'/test2': {
    		  target: 'http://localhost:8888',
    		  pathRewrite:{'^/test2':''}
    		 ......
    		},
    	  }
        }
    
    - 优点: 可以配置多个代理,且可以灵活控制请求是否走代理
    - 缺点: 配置稍繁琐,请求资源必须加前缀
    

标签:Vue,http,name,age,配置,代理服务器,axios,id
From: https://www.cnblogs.com/qinganning/p/17191803.html

相关文章

  • 直播网站源码,vue工具类,时间格式化
    直播网站源码,vue工具类,时间格式化最近做uniapp经常用到时间格式化,需要转为刚刚、几分钟前等字符串格式,自己根据需求整理了一个工具类 效果说明:时间转字符串格式,时间戳......
  • 前端路由(vue2 + vue3 + react)
    前端路由的设置:Vue2路由(vue-router3)安装插件npmivue-router@3router/index.js文件设置importVuefrom"vue";importVueRouterfrom"vue-router";Vue.use(VueRo......
  • 使用CMD命令导出和导入IIS站点配置信息
    有时候,我们可能有这个需求:某台服务器上的IIS配置了几十个网站项目,有没有一种方式可以导出这些配置,然后重装系统后(假设有这个业务场景)导入这些配置,避免一个一个的网站项目......
  • VUE定时器任务(每天12点执行)
    原文链接:https://blog.csdn.net/ITERCHARLIE/article/details/124447463设定配置datadata(){config:{time:'00:00:00',//每天几点执行interval:1,......
  • 轻量级CI/CD发布部署环境搭建及使用_07_jenkins配置pipeline
    轻量级CI/CD发布部署环境搭建及使用_07_jenkins配置pipeline尽自己的绵薄之力,为开源技术分享添砖加瓦1,设置pipeline  2,设置git仓库地址、用户名、密码 3,生成流......
  • Maven安装与配置
    Maven安装与配置下载安装下载地址:https://maven.apache.org/download.cgi下载后解压配置环境变量配置MAVEN_HOME配置Path变量win+R运行cmd,输入mvn-versio......
  • vue 过滤 懒加载 使用elementUI实现树懒加载与节点过滤功能
    vue使用elementUI实现树懒加载功能以及节点过滤 1.过滤:设置filter-node-method,值为过滤函数。2.懒加载:点击节点时才进行该层数据的获取 <el-inputplaceholder......
  • prettier常用配置
    /*prettier的配置*/"prettier.printWidth":120,//超过最大值换行"prettier.tabWidth":2,//缩进字节数"prettier.useTabs":false,//缩进不使用tab,使用空格"......
  • Vue 删除取消时报Uncaught (in promise) cancel错误解决方法
    Vue删除取消时报Uncaught(inpromise)cancel错误,如下图:   原因:this.$confirm方法内置promise方法,所以.catch()不能省略(因为取消操作时,无法捕获),虽然不影响操作,但......
  • VUE上传文件夹的三种解决方案
    ​对于大文件的处理,无论是用户端还是服务端,如果一次性进行读取发送、接收都是不可取,很容易导致内存问题。所以对于大文件上传,采用切块分段上传,从上传的效率来看,利用多线程......