1.1 使用代理服務器
1.1.1 方式一
在 vue.config.js 中添加如下配置:
devServer:{
proxy:"http://localhost:5000"
}
說明:
- 優點:配置簡單,請求資源時直接發給前端(8080)即可,
- 缺點:不能配置多個代理,不能靈活的控制請求是否走代理,
- 作業方式:若按照上述配置代理,當請求了前端不存在的資源時,那么該請求會轉發給服務器 (優先匹配前端資源)
1.1.2 方式二
撰寫 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 Vue 專案中常用的 2 個 Ajax 庫
1.2.1 Axios
-
說明:通用的
Ajax請求庫,官方推薦,使用廣泛 -
安裝:
npm install axios -
使用步驟:
-
引入
import axios from "axios"; -
使用
axios.get("http://localhost:8080/api/students").then( (response) => { console.log("請求成功了", response.data); }, (error) => { console.log("請求失敗了", error.message); } );
-
1.2.2 vue-resource
Vue 插件庫,Vue 1.x 使用廣泛,官方已不維護
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/525047.html
標籤:其他
