説明:本項目為SpringBoot項目而不是vue項目,本項目用於練習axios使用get及post請求
get和post請求都採用兩種方式進行配置,並註明易錯點
@[toc]
1.axios是什麼
Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中,axios是對ajax的一種封裝,而jquery也是對ajax的一種封裝。
axios的github:https://github.com/axios/axios
2.vue項目為什麼使用axios,而不使用jquery?
axios集成vue更好且佔內存小,而如果只用jquery的ajax的話,畢竟幾百k,$表達式也不用情況下顯得太笨重了,因此vue項目使用axios居多且集成的更好。
3.SpringBoot項目的html頁面引入axios方式,採用script引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
至於網上説的方案,對springboot項目測試無效
import axios from ‘axios’;
//安裝方法
npm install axios
//或
bower install axios
4.官網為方便起見,為所有支持的請求方法提供了別名
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
5.get請求的兩種方式
使用方式1(推薦) => axios.get();
注意1:headers請求頭設置位置不一樣,axios.get()中headers存在於{}中,而axios({})中headers當成一個key,value進行設置。
注意2:get請求參數封裝與params對象中。
axios.get("/getVue", {
params: {
name:"zhangsan"
},
headers: {
responseType: 'json' //響應數據格式為"json"
}
}).then((res)=>{
myForm.formMess.name = res.data.info.name;
myForm.formMess.password = res.data.info.password;
alert("查詢數據成功!")
}).catch(err => {
console.log(err); //打印響應數據(錯誤信息)
});
使用方式2 => axios({})
axios({
method:"get",
url:"/getVue",
params:{
name:"zhangsan"
},
headers: {
responseType: 'json' //響應數據格式為"json"
}
}).then((res)=>{
myForm.formMess.name = res.data.info.name;
myForm.formMess.password = res.data.info.password;
alert("查詢數據成功!")
}).catch(err => {
console.log(err); //打印響應數據(錯誤信息)
});
6.post請求的兩種方式
使用方式1(推薦) => axios.post();
注意點1:headers請求頭設置位置不一樣,axios.post()中headers存在於第三個{}中,而axios({})中headers當成一個key,value進行設置。
注意點2:axios.post()的第二個{}指代請求體中沒有作為key的data,而axios({})中使用data作為請求體參數。
axios.post("/addVue", {
"name":this.formMess.name,
"password":this.formMess.password
},{
headers: {
responseType: 'json'
}
}).then((res)=>{
console.log(res);
alert("提交數據成功!")
}).catch(err => {
console.log(err); //打印響應數據(錯誤信息)
});
使用方式2 => axios({})
axios({
method:"post",
url:"/addVue",
data:{
"name":this.formMess.name,
"password":this.formMess.password,
},
header:{
responseType: 'json' //響應數據格式為"json"
}
}).then((res)=>{
console.log(res);
alert("提交數據成功!")
}).catch(err => {
console.log(err); //打印響應數據(錯誤信息)
});
本人相關其他文章鏈接
1.JQuery選擇器+DOM操作+事件+DOM與JQuery對象間的轉化