网站被k怎么,搜狐做网站,装修网站官网,配置网站域名文章目录 Axios入门使用一、引言二、Axios的安装与配置1、安装Axios2、创建Axios实例 三、发送HTTP请求1、GET请求2、POST请求3、并发请求 四、配置和拦截器1、配置默认值2、拦截器 五、错误处理和取消请求1、错误处理2、取消请求 四、总结 Axios入门使用
一、引言
随着前端技… 文章目录 Axios入门使用一、引言二、Axios的安装与配置1、安装Axios2、创建Axios实例 三、发送HTTP请求1、GET请求2、POST请求3、并发请求 四、配置和拦截器1、配置默认值2、拦截器 五、错误处理和取消请求1、错误处理2、取消请求 四、总结 Axios入门使用
一、引言
随着前端技术的发展前后端分离已成为标准开发模式。Axios作为一种基于Promise的HTTP客户端被广泛应用于浏览器和node.js中用于执行HTTP请求。本篇博客将详细介绍Axios的基本使用。
二、Axios的安装与配置
1、安装Axios
首先需要安装Axios库。可以通过npm或yarn进行安装
npm install axios或者
yarn add axios也可以通过CDN直接引入到HTML文件中
script srchttps://cdn.jsdelivr.net/npm/axios/dist/axios.min.js/script2、创建Axios实例
Axios可以创建实例以便于根据不同的环境进行配置
const instance axios.create({baseURL: https://api.example.com,timeout: 1000,headers: {X-Custom-Header: foobar}
});三、发送HTTP请求
1、GET请求
使用Axios发送GET请求非常简单如下所示
axios.get(/user?ID12345).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});也可以通过params对象传递查询参数
axios.get(/user, {params: {ID: 12345}}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});2、POST请求
发送POST请求可以使用以下代码
axios.post(/user, {firstName: Fred,lastName: Flintstone}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});3、并发请求
Axios支持并发请求可以同时发送多个请求并统一处理
function getUserAccount() {return axios.get(/user/12345);
}
function getUserPermissions() {return axios.get(/user/12345/permissions);
}
axios.all([getUserAccount(), getUserPermissions()]).then(axios.spread(function (acct, perms) {//两个请求现已完成console.log(acct, perms);}));四、配置和拦截器
1、配置默认值
可以为Axios设置默认值例如
axios.defaults.baseURL https://api.example.com;
axios.defaults.headers.common[Authorization] AUTH_TOKEN;2、拦截器
Axios支持添加请求和响应拦截器
// 添加请求拦截器
axios.interceptors.request.use(function (config) {// 在发送请求之前做些什么return config;
}, function (error) {// 对请求错误做些什么return Promise.reject(error);
});// 添加响应拦截器
axios.interceptors.response.use(function (response) {// 对响应数据做点什么return response;
}, function (error) {// 对响应错误做点什么return Promise.reject(error);
});五、错误处理和取消请求
1、错误处理
Axios可以通过catch方法来处理错误
axios.get(/user/12345).catch(function (error) {if (error.response) {// 请求已发出但是服务器响应的状态码不在2xx范围内console.log(error.response.data);console.log(error.response.status);} else {// 一些在设置请求时触发的错误console.log(Error, error.message);}console.log(error.config);});2、取消请求
Axios支持取消请求
const CancelToken axios.CancelToken;
let cancel;axios.get(/user/12345, {cancelToken: new CancelToken(function executor(c) {// executor函数接收一个cancel函数作为参数cancel c;})
});// 取消请求
cancel(Operation canceled by the user.);四、总结
Axios是一个强大而灵活的HTTP客户端适用于浏览器和node.js环境。通过简单的配置和使用可以快速地进行HTTP请求并支持Promise API使得异步请求处理更加方便。掌握Axios的使用可以显著提升开发效率。 版权声明本博客内容为原创转载请保留原文链接及作者信息。
参考文章
Axios使用方法详解从入门到进阶-CSDN博客axios 全攻略