一、Axios
1、常规使用
(1).then 方式
axios.get("./js/covid-data.json ").then(res => {
this.list = res.data
console.log(this.list);
});
(2)async 方式
async mounted() {
await axios.get("./js/covid-data.json ").then(res => {
this.list = res.data
console.log(this.list);
});
})
},
2、携带请求头
语法:axios( {
url:" ",
methods:" ",
headers:" "
} )
key1Button.addEventListener('click', async () => {
// 从后台请求钥匙1的咒语部分
key1Button.disabled = true;
let { data } = await axios({
url: "/spellone",
methods: "get",
headers: { "Authorization": "2b58f9a8-7d73-4a9c-b8a2-9f05d6e8e3c7" }
})
spell1.innerHTML = data;
tryOpenTreasureBox();
});
二、Fetch
【说明】
fetch是一种在JavaScript中发送HTTP请求和获取响应的方法。
fetch使用Promise对响应进行封装,比传统的XHR请求更容易使用。
1、基本使用
fetch('url')
.then(response => response.json())
.then(data => console.log(data));
2、发送post请求【携带请求头信息】
fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'user',
password: 'pass'
})
}).then(response => response.json())
.then(data => console.log(data));
3、具体应用
web蓝桥刷题——不同食物的蛋白质占比
async function fetchData() {
// TODO:待补充代码
// 【题点1】使用fetch发送请求
const response = await fetch(MockURL);
const result = await response.json();
// 【两次await】此时拿到的数组才是纯数组
console.log(result);
// 【题点2】根据题意重构data
data.value = [{ name: "表头", icon: "none" }, ...result]
// 【题点3】需要调用【echartsInit】方法重新初始化echarts
echartsInit(data.value);
}