干翻全岛蛙蛙 发表于 2024-11-19 15:23:35

Axios的利用以及封装

一、什么是axios

Axios 是一个基于 promise 的 HTTP 库,可以用在欣赏器和 node.js 中。
特性:



[*]从欣赏器中创建 XMLHttpRequests
[*]从 node.js 创建 http 请求
[*]支持 Promise API
[*]拦截请求和响应
[*]转换请求数据和响应数据
[*]取消请求
[*]自动转换 JSON 数据
[*]客户端支持防御 XSRF
axios可以请求的方法:

get:获取数据,请求指定的信息,返回实体对象
post:向指定资源提交数据(比方表单提交或文件上传)
put:更新数据,从客户端向服务器传送的数据代替指定的文档的内容
patch:更新数据,是对put方法的增补,用来对已知资源进行局部更新
delete:请求服务器删除指定的数据
head:获取报文首部
axios中文网|axios API 中文文档 | axios
二、利用axios

安装

1.npm安装
npm install axios 2.yarn安装
yarn add axios 3.直接引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> 案例

执行get请求

    <script>
      // 为给定 ID 的 user 创建请求
      axios.get('/user?ID=12345')
            // 请求成功
            .then(function (response) {
                console.log(response);
            })
            // 请求失败
            .catch(function (error) {
                console.log(error);
            });

      // 上面的请求也可以这样做
      axios.get('/user', {
            params: {
                ID: 12345
            }
      })
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    </script> 第一段代码中查询参数ID=12345是直接附加到URL背面的。这种方式简朴直接,但假如你需要动态构建查询字符串,可能会稍显繁琐。
第二段代码中查询参数是通过params属性通报给axios.get方法的。这种方式更加机动,特别是当你需要动态构建查询参数时。Axios会自动将params对象转换成查询字符串,并将其附加到URL背面。
利用 .then() 和 .catch() 方法来处置惩罚请求乐成或失败的情况。
执行post请求

<script>
// post
// 请求体中包含了用户的firstName和lastName信息。
   axios.post('/user', {
          firstName: 'Fred',
          lastName: 'Flintstone'
      })
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
</script>
[*] axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }):这行代码向服务器的/user路径发送一个POST请求,请求体是一个对象,包含firstName和lastName两个属性,值分别为Fred和Flintstone。
[*] .then(function (response) { console.log(response); }):这是一个Promise的处置惩罚方法。假如请求乐成,服务器返回响应,这个响应会被通报给.then方法的回调函数。在这个例子中,回调函数简朴地打印出响应。
[*] .catch(function (error) { console.log(error); });:这也是一个Promise的处置惩罚方法。假如请求失败,比如网络题目或服务器错误,错误会被通报给.catch方法的回调函数。在这个例子中,回调函数简朴地打印出错误信息。
执行多个并发请求

<script>
// 执行多个并发请求
      function getUserAccount() {
            return axios.get('/user/12345');
      }

      function getUserPermissions() {
            return axios.get('/user/12345/permissions');
      }

      axios.all()
            .then(axios.spread(function (acct, perms) {
                // 两个请求现在都执行完成
            }));
</script> 利用了 axios.all 和 axios.spread 来同时处置惩罚两个异步的 Axios GET 请求,并在它们都完成后执行一些操作


[*] getUserAccount 和 getUserPermissions 函数分别发起一个 Axios GET 请求来获取用户账户和权限。
[*] axios.all 方法接受一个包含两个 Promise 的数组(由 getUserAccount() 和 getUserPermissions() 返回的 Promise)。
[*] axios.spread 方法是一个用于处置惩罚 axios.all 返回的结果的实用工具。它将 axios.all 的结果数组展开为单独的参数,并通报给提供的回调函数。
[*] 在回调函数中,您可以访问两个请求的响应,并分别处置惩罚它们。
[*].catch 方法用于捕捉并处置惩罚在请求过程中可能发生的任何错误。
axios API

Axios 提供了一个简朴的 API 来发送各种 HTTP 请求,并处置惩罚响应。以下是 Axios API 的一些常用方法和特性:
创建实例:

创建一个 Axios 实例,并设置一些默认的请求参数:
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
发送请求

Axios 提供了以下方法来发送 HTTP 请求:
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]]) 此中,url 是请求的 URL,data 是作为请求主体被发送的数据,config 是请求的设置选项
请求设置

请求设置可以包含以部属性:


[*] url:请求的 URL。
[*] method:创建请求时利用的方法(默认是 get)。
[*] headers:自界说请求头。
[*] params:要与请求一起发送的 URL 参数。
[*] data:作为请求主体被发送的数据。
[*] timeout:指定请求超时的毫秒数(0 表现无超时时间)。
[*] ... 等等。
这些是创建请求时可以用的设置选项。只有 url 是必须的。假如没有指定 method,请求将默认利用 get 方法。
{
   // `url` 是用于请求的服务器 URL
url: '/user',

// `method` 是创建请求时使用的方法
method: 'get', // default

// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://some-domain.com/api/',

// `transformRequest` 允许在向服务器发送前,修改请求数据
// 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data, headers) {
    // 对 data 进行任意转换处理
    return data;
}],

// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
    // 对 data 进行任意转换处理
    return data;
}],

// `headers` 是即将被发送的自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},

// `params` 是即将与请求一起发送的 URL 参数
// 必须是一个无格式对象(plain object)或 URLSearchParams 对象
params: {
    ID: 12345
},

   // `paramsSerializer` 是一个负责 `params` 序列化的函数
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
},

// `data` 是作为请求主体被发送的数据
// 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
// 在没有设置 `transformRequest` 时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属:FormData, File, Blob
// - Node 专属: Stream
data: {
    firstName: 'Fred'
},

// `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
// 如果请求话费了超过 `timeout` 的时间,请求将被中断
timeout: 1000,

   // `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // default

// `adapter` 允许自定义处理请求,以使测试更轻松
// 返回一个 promise 并应用一个有效的响应 (查阅 (#response-api)).
adapter: function (config) {
    /* ... */
},

// `auth` 表示应该使用 HTTP 基础验证,并提供凭据
// 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
auth: {
    username: 'janedoe',
    password: 's00pers3cret'
},

   // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default

// `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default

   // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default

// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default

   // `onUploadProgress` 允许为上传处理进度事件
onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
},

// `onDownloadProgress` 允许为下载处理进度事件
onDownloadProgress: function (progressEvent) {
    // 对原生进度事件的处理
},

   // `maxContentLength` 定义允许的响应内容的最大尺寸
maxContentLength: 2000,

// `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 rejectpromise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
validateStatus: function (status) {
    return status >= 200 && status < 300; // default
},

// `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
// 如果设置为0,将不会 follow 任何重定向
maxRedirects: 5, // default

// `socketPath` defines a UNIX Socket to be used in node.js.
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
// Only either `socketPath` or `proxy` can be specified.
// If both are specified, `socketPath` is used.
socketPath: null, // default

// `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
// `keepAlive` 默认没有启用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),

// 'proxy' 定义代理服务器的主机名称和端口
// `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
// 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
},

// `cancelToken` 指定用于取消请求的 cancel token
// (查看后面的 Cancellation 这节了解更多)
cancelToken: new CancelToken(function (cancel) {
})
} 响应结构


{
data: {}, // 服务器提供的响应
status: 200, // 来自服务器响应的 HTTP 状态码
statusText: 'OK', // HTTP状态信息
headers: {}, // 服务器响应的头
config: {}, // 请求的配置信息
request: {}// 请求的 XMLHttpRequest 对象 (仅限浏览器)
} 并发请求

Axios 提供了 axios.all 方法来同时执行多个请求,并利用 axios.spread 方法来处置惩罚全部请求的响应:
axios.all()
.then(axios.spread((user, permissions) => {
    // 两个请求都完成了
}));
拦截器

可以在请求或响应被 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);
});
错误处置惩罚

axios.get('/user/12345')
.catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
}); 三、Axios封装

Axios 封装是一个常见的实践,旨在简化 HTTP 请求的利用,同时保持代码的整洁和可维护性。通过封装 Axios,可以创建自界说的请求函数,处置惩罚错误,设置请求超时,以及添加其他通用的请求设置。
import axios from 'axios';

// 创建 axios 实例
const http = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000, // 请求超时时间
});

// 请求拦截器
http.interceptors.request.use(
(config) => {
    // 在发送请求之前做些什么,比如设置请求头
    config.headers['Content-Type'] = 'application/json';
    // 可以添加更多的请求头或进行其他配置
    return config;
},
(error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
}
);

// 响应拦截器
http.interceptors.response.use(
(response) => {
    // 对响应数据做点什么
    // 你可以在这里根据状态码或其他条件处理响应
    return response;
},
(error) => {
    // 对响应错误做点什么
    // 你可以在这里统一处理错误,比如显示错误信息
    return Promise.reject(error);
}
);

// 封装 GET 请求
function get(url, params = {}) {
return http.get(url, { params });
}

// 封装 POST 请求
function post(url, data = {}) {
return http.post(url, data);
}

// 导出封装好的请求方法
export { get, post };
创建了一个 Axios 实例,并设置了根本的 URL 和超时时间。然后,添加了请求和响应拦截器,以便在请求发送之前和响应返回之后执行一些自界说逻辑。最后,封装了 GET 和 POST 请求方法,并导出了这些方法,以便在其他文件中利用。
如今,你可以在应用程序中的任何地方导入并利用这些封装好的请求方法,比方:
import { get, post } from './path/to/axios-wrapper';

get('/users')
.then((response) => {
    console.log(response.data);
})
.catch((error) => {
    console.error(error);
});

post('/users', { name: 'John Doe', age: 30 })
.then((response) => {
    console.log(response.data);
})
.catch((error) => {
    console.error(error);
});


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Axios的利用以及封装