1.Axios 是一个基于 Promise 的现代化 HTTP 客户端库,适用于浏览器和 Node.js 环境。
2.在axios里有几种基础请求方法,在网课学习里面我们使用基础请求方法与现在用的不大相同,在网课中我们一般用以下格式
axios({
url: 'http://hmajax.itheima.net/api/login',
method: 'POST',//选择请求方式
data: {
username,
password
}
}).then(result => {
alertFn(result.data.message, true)
}).catch(error => {
console.log(error);
alertFn(error.response.data.message, false)
})
2.1GET 请求
这种书写方式使代码更加简便,而且目的更加明了,以后在写代码的时候我也会使用这种方法。而他书写参数的方法和之前的一样,方式一:URL 中直接拼接参数,方式二:通过 params
对象传递(推荐)。
axios.get('https://api.example.com/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
2.2 POST 请求
axios.post('/user', {
firstName: '张',
lastName: '三',
age: 30
})
.then(response => {
console.log(response.data);
});
2.3 其他请求方法
// PUT 请求
axios.put('/user/123', {
name: '李四'
});
// DELETE 请求
axios.delete('/user/123');
// PATCH 请求
axios.patch('/user/123', {
name: '王五'
});
// HEAD 请求
axios.head('/user');
3.请求拦截器
请求拦截器是 Axios 中一个强大的功能,允许你在请求发送到服务器之前对请求进行拦截和处理。
请求拦截器是在请求被发送之前执行的函数,可以用于:修改请求配置,添加认证信息,设置全局请求头,记录请求日志,验证请求参数
这段代码可以添加请求拦截器
axios.interceptors.request.use(
config => {
// 在发送请求前做些什么
return config;
},
error => {
// 对请求错误做些什么
return Promise.reject(error);
}
);