Vue2利用Axios發(fā)起請求的詳細(xì)過程記錄
前言
當(dāng)你看到該文章時希望你已知曉什么是跨域請求以及跨域請求的處理,本文不會贅述
本文后臺基于Springboot2.3進(jìn)行搭建,Controller中不會寫任何業(yè)務(wù)邏輯僅用于配合前端調(diào)試
Controller中使用的R.success為本人封裝的工具類,代碼在文末
Axios的安裝和配置
在項目目錄下執(zhí)行命令安裝axios
npm install -S axios
打開src路徑下的main.js文件,在文件中引入axios依賴并掛載到vue全局屬性中
// 引用axios依賴 import axios from 'axios' // 掛在到vue中,這里將axios掛載為request,在組件中就可以使用this.request來調(diào)用axios了 Vue.prototype.request = axios;
發(fā)起GET請求調(diào)用的是axios中的get方法,點進(jìn)去可以看到該方法接收了url和config兩個對象

發(fā)起簡單GET請求
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/list")
public R list() {
return R.success("用戶列表查詢成功!");
}
}
<template>
<div id="index">
<button @click="selectList">查詢用戶</button>
</div>
</template>
<script>
export default {
name: "index",
methods: {
selectList() {
// 簡單GET請求只需要傳入URL就可以實現(xiàn)
this.request.get("http://localhost:8000/user/list").then(res => {
console.log("res", res);
}).catch(e => {
console.log("e", e);
})
}
}
}
</script>
<style></style>

發(fā)起簡單GET請求并攜帶參數(shù)
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/get")
public R get(String id) {
return R.success("用戶獲取成功!");
}
}
selectOne() {
let config = {
params: {id: "1"}
}
// url后面跟上config對象,config對象中的params屬性對應(yīng)的就是請求參數(shù)
this.request.get("http://localhost:8000/user/get", config).then(res => {
console.log("res", res);
}).catch(e => {
console.log("e", e);
})
},

發(fā)起POST請求
發(fā)起POST請求調(diào)用的是axios中的post方法,點進(jìn)去可以看到該方法的參數(shù)列表有三個對象

發(fā)起簡單POST請求
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/save")
public R save() {
return R.success("用戶添加成功!");
}
}
save() {
// 發(fā)送簡單POST請求與簡單GET請求雷同,只需要將get方法修改為post方法即可
this.request.post("http://localhost:8000/user/save").then(res => {
console.log("res", res);
}).catch(e => {
console.log("e", e);
})
},

發(fā)起POST請求并攜帶參數(shù)(一)
@RestController
@RequestMapping("/user")
public class UserController {
/**
* 一般發(fā)起POST請求都是將參數(shù)放在請求體中,然后在通過@RequestBody進(jìn)行解析的
* 這里我就不創(chuàng)建實體類了,直接使用Map集合來接收一下
*/
@PostMapping("/save")
public R save(@RequestBody Map<String, String> data) {
return R.success("用戶添加成功!")
.setAttribute("name", data.get("username"))
.setAttribute("pwd", data.get("password"));
}
}
save() {
let data = {
username: "Java小學(xué)生丶",
password: "123456789"
}
// 當(dāng)看到參數(shù)列表的時候應(yīng)該就能猜出來,直接將對象放在第二個參數(shù)上就可以
// 需要注意的是這種方法攜帶的參數(shù)是放在請求體中的
this.request.post("http://localhost:8000/user/save", data).then(res => {
console.log("res", res);
}).catch(e => {
console.log("e", e);
})
},

發(fā)起POST請求并攜帶參數(shù)(二)
上面說直接使用data傳遞參數(shù)是放在請求體中的,需要后端使用@RequestBody才能取到,這里將參數(shù)改為路徑參數(shù)進(jìn)行提交
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/save")
public R save(String username, String password) {
return R.success("用戶添加成功!")
.setAttribute("name", username)
.setAttribute("pwd", password);
}
}
save() {
let config = {
params: {
username: "Java小學(xué)生丶",
password: "123456789"
}
}
// 這里不使用data,改用config進(jìn)行傳參,還是將對象封裝為params進(jìn)行傳遞
this.request.post("http://localhost:8000/user/save", null, config).then(res => {
console.log("res", res);
}).catch(e => {
console.log("e", e);
})
},

上傳文件測試
除開GET、POST請求之外,還有PUT、DELETE等等類型的請求,這里就不一一測試了,來了解一下上傳文件
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/upload")
public R upload(MultipartFile file, String fileName) {
// file對象就是接收到的文件,針對文件的處理邏輯省略不寫...
return R.success("文件上傳成功!")
.setAttribute("fileName", fileName);
}
<template>
<div id="index">
<!-- input:file 用于選擇文件,選擇文件后觸發(fā)change事件調(diào)用fileChange方法 -->
<input type="file" id="file" @change="fileChange" />
<!-- 執(zhí)行上傳文件的方法 -->
<button @click="upload">點擊上傳</button>
</div>
</template>
<script>
export default {
name: "index",
data() {
return {
file: null
}
},
methods: {
fileChange(event) {
// 當(dāng)選擇了某個文件后會觸發(fā)該方法,將文件對象存放到file中
this.file = event.target.files[0];
},
upload() {
// 創(chuàng)建一個FormData對象,將file放進(jìn)去,也可以放一些其他參數(shù)
let data = new FormData();
data.append('file', this.file);
data.append('fileName', "11223344.txt");
// 創(chuàng)建config對象,設(shè)置請求頭類型為multipart/form-data
let config = {
headers: {'Content-Type': 'multipart/form-data'}
}
// 發(fā)起請求攜帶剛剛創(chuàng)建的對象
this.request.post('http://localhost:8000/user/upload', data, config).then(res => {
console.log("res", res);
})
}
}
}
</script>

Axios的config配置
通過觀察可以發(fā)現(xiàn)Axios的請求都會接收一個config對象,可以在node_modules/axios/index.d.ts文件看到該配置的詳細(xì)信息:

配置項有很多,我也是個新人好多沒接觸過,這里就簡單測試幾個其他隨時用隨時查,推薦一個Axios中文網(wǎng)

baseURL
baseURL是個比較常用的屬性,可以針對每個請求設(shè)置根地址,我們在發(fā)起請求時只需要關(guān)注請求路徑即可
<script>
export default {
name: "index",
data() {
return {
config: {
baseURL: "http://localhost:8000"
}
}
},
methods: {
test() {
let data = {name: "Java小學(xué)生丶"};
this.request.post("/user/save", data, this.config).then(res => {
console.log("res", res);
});
},
}
}
</script>
timeout
timeout也屬于比較常用的配置項,用于配置請求的超時時間,單位是毫秒ms,設(shè)置為0代表不設(shè)置超時時間
<script>
export default {
name: "index",
data() {
return {
config: {
baseURL: "http://localhost:8000",
timeout: 5000
}
}
},
methods: {
test() {
let data = {name: "張涵哲"};
this.request.post("/user/save", data, this.config).then(res => {
console.log("res", res);
});
},
}
}
</script>

withCredentials
該屬性同樣比較常用,withCredentials的值為bool類型,用于設(shè)置是否允許攜帶Cookie,Axios請求默認(rèn)是不允許攜帶Cookie的,可以通過Controller打印sessionID進(jìn)行測試

<script>
export default {
name: "index",
data() {
return {
config: {
baseURL: "http://localhost:8000",
// 需要服務(wù)端進(jìn)行配合
withCredentials: true,
timeout: 5000
}
}
},
methods: {
test() {
let data = {name: "Java小學(xué)生丶"};
this.request.post("/user/save", data, this.config).then(res => {
console.log("res", res);
});
},
}
}
</script>

Axios暫時就寫到這里,了解這些日常開發(fā)基本不成問題了,用熟config后可以試著封裝一個工具類
總結(jié)
到此這篇關(guān)于Vue2利用Axios發(fā)起請求的文章就介紹到這了,更多相關(guān)Vue2用Axios發(fā)起請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue.js 雙層嵌套for遍歷的方法詳解, 類似php foreach()
今天小編就為大家分享一篇vue.js 雙層嵌套for遍歷的方法詳解, 類似php foreach(),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
在vue中實現(xiàn)清除echarts上次保留的數(shù)據(jù)(親測有效)
這篇文章主要介紹了在vue中實現(xiàn)清除echarts上次保留的數(shù)據(jù)(親測有效),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
vue3?setup中父組件通過Ref調(diào)用子組件的方法(實例代碼)
這篇文章主要介紹了vue3?setup中父組件通過Ref調(diào)用子組件的方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08

