????????axios 它的底層是用了 XMLHttpRequest(xhr)方式發(fā)送請(qǐng)求和接收響應(yīng),xhr 相對(duì)于之前講過的 fetch api 來說,功能更強(qiáng)大,但由于是比較老的 api,不支持 Promise,axios 對(duì) xhr 進(jìn)行了封裝,使之支持 Promise,并提供了對(duì)請(qǐng)求、響應(yīng)的統(tǒng)一攔截功能
安裝
沒下載nvm你就不要試了
npm install axios -S
代碼導(dǎo)入
import axios from 'axios'
-
axios 默認(rèn)導(dǎo)出一個(gè)對(duì)象,這里的 import 導(dǎo)入的就是它默認(rèn)導(dǎo)出的對(duì)象
后面會(huì)有代碼案例供參考
方法
?
-
config - 選項(xiàng)對(duì)象、例如查詢參數(shù)、請(qǐng)求頭...
-
data - 請(qǐng)求體數(shù)據(jù)、最常見的是 json 格式數(shù)據(jù)
-
get、head 請(qǐng)求無法攜帶請(qǐng)求體,這應(yīng)當(dāng)是瀏覽器的限制所致(xhr、fetch api 均有限制)
-
options、delete 請(qǐng)求可以通過 config 中的 data 攜帶請(qǐng)求體
<template>
<div>
<input type="button" value="獲取遠(yuǎn)程數(shù)據(jù)" @click="sendReq()">
</div>
</template>
<script>
import axios from 'axios'
const options = {
methods: {
async sendReq() {
// 1. 演示 get, post
// const resp = await axios.post('/api/a2');
// 2. 發(fā)送請(qǐng)求頭
// const resp = await axios.post('/api/a3',{},{
// headers:{
// Authorization:'abc'
// }
// });
// 3. 發(fā)送請(qǐng)求時(shí)攜帶查詢參數(shù) ?name=xxx&age=xxx 特殊符號(hào)需要手動(dòng)編碼
// const name = encodeURIComponent('&&&');
// const age = 18;
// const resp = await axios.post(`/api/a4?name=${name}&age=${age}`);
// 不想自己拼串、處理特殊字符、就用下面的辦法
// const resp = await axios.post('/api/a4', {}, {
// params: {
// name:'&&&&',
// age: 20
// }
// });
// 4. 用請(qǐng)求體發(fā)數(shù)據(jù),格式為 urlencoded,,參數(shù)為對(duì)象時(shí)使用
// const params = new URLSearchParams();
// params.append("name", "張三");
// params.append("age", 24)
// const resp = await axios.post('/api/a4', params);
// 5. 用請(qǐng)求體發(fā)數(shù)據(jù),格式為 multipart,參數(shù)為對(duì)象時(shí)使用
// const params = new FormData();
// params.append("name", "李四");
// params.append("age", 30);
// const resp = await axios.post('/api/a5', params);
// 6. 用請(qǐng)求體發(fā)數(shù)據(jù),格式為 json,參數(shù)為對(duì)象時(shí)使用
const resp = await axios.post('/api/a5json', {
name: '王五',
age: 50
});
console.log(resp);
}
}
};
export default options;
</script>
創(chuàng)建實(shí)例——升級(jí)版
const _axios = axios.create(config);
-
axios 對(duì)象可以直接使用,但使用的是默認(rèn)的設(shè)置
-
用 axios.create 創(chuàng)建的對(duì)象,可以覆蓋默認(rèn)設(shè)置,config 見下面說明
?
const _axios = axios.create({
baseURL: 'http://localhost:8080',
withCredentials: true
});
await _axios.post('/api/a6set')
await _axios.post('/api/a6get')
這里走的就不是vue.config.js中的配置了
-
生產(chǎn)環(huán)境希望 xhr 請(qǐng)求不走代理,可以用 baseURL 統(tǒng)一修改
-
希望跨域請(qǐng)求攜帶 cookie,需要配置 withCredentials: true,服務(wù)器也要配置 allowCredentials = true,否則瀏覽器獲取跨域返回的 cookie 時(shí)會(huì)報(bào)錯(cuò)
響應(yīng)格式
?這是后端返回給前端獲取到的對(duì)象的響應(yīng)內(nèi)容
-
200 表示響應(yīng)成功
-
400 請(qǐng)求數(shù)據(jù)不正確 age=abc
-
401 身份驗(yàn)證沒通過
-
403 沒有權(quán)限
-
404 資源不存在
-
405 不支持請(qǐng)求方式 post文章來源:http://www.zghlxwxcb.cn/news/detail-471185.html
-
500 服務(wù)器內(nèi)部錯(cuò)誤文章來源地址http://www.zghlxwxcb.cn/news/detail-471185.html
到了這里,關(guān)于Axios后端程序員快速入門簡述的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!