1. 程式人生 > >vue中跨域解決辦法

vue中跨域解決辦法

專案在上線之後,前後端的程式碼放在同一個伺服器下面,就不存在跨域的問題。然而在前後端分離的開發中,跨域在所難免。在以前,存在跨域的時候一般都叫後臺小夥伴設定,但是vue中提供了一種方法,在前端也可以設定解決跨域的問題。下面給大家介紹一下:

一、修改config資料夾中index.js檔案dev:{。。。}

proxyTable: {
			"/api": {
				target: "http://loacalhost:3000",
				changeOrigin: true,
				pathRewrite: {
					'^/api': ''
				}
			}
		}

二、在main.js中新增HOST

Vue.prototype.HOST = '/api'

然後我們就可以在給後臺傳送請求時寫成:

		created(){
			var url = this.HOST+'/login';
			this.$axios.post(url,{
					username: 'gdou',
					password: '2015116414xx'
			})
			.then(res => {
				console.log(res.data)
			})
			.catch(error => {
				console.log(error)
			})
		}

我們修改了配置檔案,別忘了重啟服務哦~~