【前端VUE基础(五)】Axios 的常用语法
Axios 是一个常用的基于 Promise 的 HTTP 客户端库,可用于在浏览器和 Node.js 中发送 HTTP 请求,使用.then()来处理成功的响应,.catch()来处理错误。
·
目录
Axios 是一个常用的基于 Promise 的 HTTP 客户端库,可用于在浏览器和 Node.js 中发送 HTTP 请求,使用
.then()
来处理成功的响应,.catch()
来处理错误。下面是 Axios 常用写法:
一、最基础的方法
1、Axios最基本的写法:
(1)普通函数写法
axios.get('/api/users')
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.error(error);
});
(2)箭头函数写法
axios.get('/api/users')
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
2、使用axios()函数并传递配置对象:
(1)普通函数
axios({
method: 'get',
url: '/api/users'
})
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.error(error);
});
(2)箭头函数
axios({
method: 'get',
url: '/api/users'
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
3、使用async/await语法:
(1)普通函数
async function fetchData() {
try {
const response = await axios.get('/api/users');
console.log(response.data);
} catch (error) {
console.error(error);
}
}
fetchData();
(2)箭头函数
async function fetchData() {
try {
const response = await axios.get('/api/users');
console.log(response.data);
} catch (error) {
console.error(error);
}
}
fetchData();
二、在axios请求中携带参数
1、使用axios.get()函数:
axios.get('/api/users', {
params: {
param1: 'value1',
param2: 'value2'
}
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
2、使用axios()函数并传递配置对象:
axios({
method: 'get',
url: '/api/users',
params: {
param1: 'value1',
param2: 'value2'
}
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
3、使用async/await语法:
const fetchData = async () => {
try {
const response = await axios.get('/api/users', {
params: {
param1: 'value1',
param2: 'value2'
}
});
console.log(response.data);
} catch (error) {
console.error(error);
}
};
fetchData();
三、给后端发送数据
1、使用axios.post()
函数:
const sendData = {
id: 1,
name: "张三"
};
axios.post('/api/users', sendData)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
2、使用axios()
函数并传递配置对象:
const sendData = {
id: 1,
name: "张三"
};
axios({
method: 'post',
url: '/api/users',
data: sendData
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
3、使用async/await语法:
const sendData = {
id: 1,
name: "张三"
};
const postData = async () => {
try {
const response = await axios.post('/api/users', sendData);
console.log(response.data);
} catch (error) {
console.error(error);
}
};
postData();
在使用async/await语法时,使用try/catch块来捕获可能的错误。
更多推荐
已为社区贡献2条内容
所有评论(0)