天天看點

Vue入門019- 開啟代理請求資源,解決開發時候的跨域問題

作者:CShap新勢力

我有2個伺服器資源

擷取學生資訊

http://localhost:5000/students

Vue入門019- 開啟代理請求資源,解決開發時候的跨域問題

學生資源

擷取汽車資訊

http://localhost:5001/cars

Vue入門019- 開啟代理請求資源,解決開發時候的跨域問題

汽車資源

如果後端沒有對CORS做任何配置,那麼下面的代碼會有跨域的錯誤

getStudents(){
				axios.get('http://localhost:5000/students').then(
					response => {
						console.log('請求成功了',response.data)
					},
					error => {
						console.log('請求失敗了',error.message)
					}
				)
},           
Vue入門019- 開啟代理請求資源,解決開發時候的跨域問題

跨域錯誤

這個時候,我們不想麻煩後端,那麼代理就出來了

配置代理

module.exports = {
  pages: {
    index: {
      //入口
      entry: 'src/main.js',
    },
  },
	lintOnSave:false, //關閉文法檢查
	//開啟代理伺服器(方式一)
	/* devServer: {
    proxy: 'http://localhost:5000'
  }, */
	//開啟代理伺服器(方式二)
	devServer: {
    proxy: {
      '/atguigu': {
        target: 'http://localhost:5000',
				pathRewrite:{'^/atguigu':''},
        // ws: true, //用于支援websocket
        // changeOrigin: true //用于控制請求頭中的host值
      },
      '/demo': {
        target: 'http://localhost:5001',
				pathRewrite:{'^/demo':''},
        // ws: true, //用于支援websocket
        // changeOrigin: true //用于控制請求頭中的host值
      }
    }
  }
}           

通過通路代理擷取資料

<template>
	<div>
		<button @click="getStudents">擷取學生資訊</button>
		<button @click="getCars">擷取汽車資訊</button>
	</div>
</template>

<script>
	import axios from 'axios'
	export default {
		name:'App',
		methods: {
			getStudents(){
				axios.get('http://localhost:8080/atguigu/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>           

上面代碼擷取資料的流程

App.vue--->proxy--->server

vue腳手架配置代理

方法一

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

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

說明:

1. 優點:配置簡單,請求資源時直接發給前端(8080)即可。

2. 缺點:不能配置多個代理,不能靈活的控制請求是否走代理。

3. 工作方式:若按照上述配置代理,當請求了前端不存在的資源時,那麼該請求會轉發給伺服器 (優先比對前端資源),如果前端存在資源就不會轉發了

方法二

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. 缺點:配置略微繁瑣,請求資源時必須加字首。

npm i axios

安裝 axios

代碼摘錄于尚矽谷Vue學習課件

繼續閱讀