Ajax异步请求 axios
Axios 是一个基于 Promise 的 HTTP 客户端,实用于欣赏器和 node.js。它提供了从欣赏器中创建 XMLHttpRequests 和从 node.js 创建 http 请求的简洁 API。由于 Axios 利用了 Promise API,你可以利用 async/await 或 .then()/.catch()` 方法来处理异步请求。
安装 Axios
假如你在利用 npm 或 yarn,可以通过以下下令安装 Axios:
- npm install axios
- # 或者
- yarn add axios
复制代码 利用 Axios 发送 GET 请求
- // 引入 axios
- const axios = require('axios');
-
- // 发送 GET 请求
- axios.get('https://api.example.com/data')
- .then(function (response) {
- // 处理成功情况
- console.log(response);
- })
- .catch(function (error) {
- // 处理错误情况
- console.log(error);
- })
- .then(function () {
- // 总是会执行
- });
-
- // 使用 async/await
- async function fetchData() {
- try {
- const response = await axios.get('https://api.example.com/data');
- console.log(response.data);
- } catch (error) {
- console.error(error);
- }
- }
-
- fetchData();
复制代码 利用 Axios 发送 POST 请求
- // 发送 POST 请求
- axios.post('https://api.example.com/users', {
- firstName: 'Fred',
- lastName: 'Flintstone'
- })
- .then(function (response) {
- console.log(response);
- })
- .catch(function (error) {
- console.log(error);
- });
-
- // 使用 async/await
- async function createUser() {
- try {
- const response = await axios.post('https://api.example.com/users', {
- firstName: 'Fred',
- lastName: 'Flintstone'
- });
- console.log(response.data);
- } catch (error) {
- console.error(error);
- }
- }
-
- createUser();
复制代码 配置请求
Axios 允许你配置请求,好比设置请求头(headers)、超时时间(timeout)等。
- axios.get('https://api.example.com/data', {
- params: {
- ID: 12345
- },
- timeout: 1000,
- headers: {'X-Custom-Header': 'foobar'}
- })
- .then(function (response) {
- console.log(response.data);
- })
- .catch(function (error) {
- if (error.response) {
- // 请求已发出,但服务器响应的状态码不在 2xx 的范围内
- console.log(error.response.data);
- console.log(error.response.status);
- console.log(error.response.headers);
- } else if (error.request) {
- // 请求已经发起,但没有收到响应
- console.log(error.request);
- } else {
- // 设置请求时触发的错误
- console.log('Error', error.message);
- }
- console.log(error.config);
- });
复制代码 拦截请求和响应
Axios 允许你在请求或响应被 then 或 catch 处理前拦截它们。
- // 添加请求拦截器
- 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);
- });
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |