ToB企服应用市场:ToB评测及商务社交产业平台

标题: axios入门 [打印本页]

作者: 忿忿的泥巴坨    时间: 2024-10-30 02:16
标题: axios入门
axios入门

axios是什么?

axios是前端最常用的Ajax请求库
官方文档:https://github.com/axios/axios
axios的特点

基于xhr+promise的异步ajax请求库
欣赏器端/node端都能使用
支持请求/相应拦截
支持请求取消
请求/相应数据转换,能主动转为JSON
批量发送多个请求
常用语法

axios(config):通用/最本质的发送恣意请求的方式
  1. axios({
  2.         //常用的配置项
  3.         method:'',                //GET  POST   PUT 更新   DELETE 删除
  4.         url:'',   //不同的method需要到的目录下不一样,可以参考官方文档
  5.         //响应体
  6.         data:{},
  7.         //响应头
  8.         headers:{}
  9. })
复制代码
Request Config

These are the available config options for making requests. Only the url is required. Requests will default to GET if method is not specified.
  1. {
  2.   // `url` is the server URL that will be used for the request
  3.   url: '/user',
  4.   // `method` is the request method to be used when making the request
  5.   method: 'get', // default
  6.   // `baseURL` will be prepended to `url` unless `url` is absolute.
  7.   // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  8.   // to methods of that instance.
  9.   baseURL: 'https://some-domain.com/api/',
  10.   // `transformRequest` allows changes to the request data before it is sent to the server
  11.   // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  12.   // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  13.   // FormData or Stream
  14.   // You may modify the headers object.
  15.   transformRequest: [function (data, headers) {
  16.     // Do whatever you want to transform the data
  17.     return data;
  18.   }],
  19.   // `transformResponse` allows changes to the response data to be made before
  20.   // it is passed to then/catch
  21.   transformResponse: [function (data) {
  22.     // Do whatever you want to transform the data
  23.     return data;
  24.   }],
  25.   // `headers` are custom headers to be sent
  26.   headers: {'X-Requested-With': 'XMLHttpRequest'},
  27.   // `params` are the URL parameters to be sent with the request
  28.   // Must be a plain object or a URLSearchParams object
  29.   params: {
  30.     ID: 12345
  31.   },
  32.   
  33.   // `paramsSerializer` is an optional config that allows you to customize serializing `params`.
  34.   paramsSerializer: {
  35.     //Custom encoder function which sends key/value pairs in an iterative fashion.
  36.     encode?: (param: string): string => { /* Do custom operations here and return transformed string */ },
  37.    
  38.     // Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour.
  39.     serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ),
  40.    
  41.     //Configuration for formatting array indexes in the params.
  42.     indexes: false // Three available options: (1) indexes: null (leads to no brackets), (2) (default) indexes: false (leads to empty brackets), (3) indexes: true (leads to brackets with indexes).   
  43.   },
  44.   // `data` is the data to be sent as the request body
  45.   // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
  46.   // When no `transformRequest` is set, must be of one of the following types:
  47.   // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  48.   // - Browser only: FormData, File, Blob
  49.   // - Node only: Stream, Buffer, FormData (form-data package)
  50.   data: {
  51.     firstName: 'Fred'
  52.   },
  53.   // syntax alternative to send data into the body
  54.   // method post
  55.   // only the value is sent, not the key
  56.   data: 'Country=Brasil&City=Belo Horizonte',
  57.   // `timeout` specifies the number of milliseconds before the request times out.
  58.   // If the request takes longer than `timeout`, the request will be aborted.
  59.   timeout: 1000, // default is `0` (no timeout)
  60.   // `withCredentials` indicates whether or not cross-site Access-Control requests
  61.   // should be made using credentials
  62.   withCredentials: false, // default
  63.   // `adapter` allows custom handling of requests which makes testing easier.
  64.   // Return a promise and supply a valid response (see lib/adapters/README.md)
  65.   adapter: function (config) {
  66.     /* ... */
  67.   },
  68.   // Also, you can set the name of the built-in adapter, or provide an array with their names
  69.   // to choose the first available in the environment
  70.   adapter: 'xhr' // 'fetch' | 'http' | ['xhr', 'http', 'fetch']
  71.   // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  72.   // This will set an `Authorization` header, overwriting any existing
  73.   // `Authorization` custom headers you have set using `headers`.
  74.   // Please note that only HTTP Basic auth is configurable through this parameter.
  75.   // For Bearer tokens and such, use `Authorization` custom headers instead.
  76.   auth: {
  77.     username: 'janedoe',
  78.     password: 's00pers3cret'
  79.   },
  80.   // `responseType` indicates the type of data that the server will respond with
  81.   // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
  82.   //   browser only: 'blob'
  83.   responseType: 'json', // default
  84.   // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
  85.   // Note: Ignored for `responseType` of 'stream' or client-side requests
  86.   // options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',
  87.   // 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',
  88.   // 'utf8', 'UTF8', 'utf16le', 'UTF16LE'
  89.   responseEncoding: 'utf8', // default
  90.   // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  91.   xsrfCookieName: 'XSRF-TOKEN', // default
  92.   // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  93.   xsrfHeaderName: 'X-XSRF-TOKEN', // default
  94.    
  95.   // `undefined` (default) - set XSRF header only for the same origin requests
  96.   withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),
  97.   // `onUploadProgress` allows handling of progress events for uploads
  98.   // browser & node.js
  99.   onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
  100.     // Do whatever you want with the Axios progress event
  101.   },
  102.   // `onDownloadProgress` allows handling of progress events for downloads
  103.   // browser & node.js
  104.   onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
  105.     // Do whatever you want with the Axios progress event
  106.   },
  107.   // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
  108.   maxContentLength: 2000,
  109.   // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
  110.   maxBodyLength: 2000,
  111.   // `validateStatus` defines whether to resolve or reject the promise for a given
  112.   // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  113.   // or `undefined`), the promise will be resolved; otherwise, the promise will be
  114.   // rejected.
  115.   validateStatus: function (status) {
  116.     return status >= 200 && status < 300; // default
  117.   },
  118.   // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  119.   // If set to 0, no redirects will be followed.
  120.   maxRedirects: 21, // default
  121.   // `beforeRedirect` defines a function that will be called before redirect.
  122.   // Use this to adjust the request options upon redirecting,
  123.   // to inspect the latest response headers,
  124.   // or to cancel the request by throwing an error
  125.   // If maxRedirects is set to 0, `beforeRedirect` is not used.
  126.   beforeRedirect: (options, { headers }) => {
  127.     if (options.hostname === "example.com") {
  128.       options.auth = "user:password";
  129.     }
  130.   },
  131.   // `socketPath` defines a UNIX Socket to be used in node.js.
  132.   // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  133.   // Only either `socketPath` or `proxy` can be specified.
  134.   // If both are specified, `socketPath` is used.
  135.   socketPath: null, // default
  136.   
  137.   // `transport` determines the transport method that will be used to make the request. If defined, it will be used. Otherwise, if `maxRedirects` is 0, the default `http` or `https` library will be used, depending on the protocol specified in `protocol`. Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol, which can handle redirects.
  138.   transport: undefined, // default
  139.   // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  140.   // and https requests, respectively, in node.js. This allows options to be added like
  141.   // `keepAlive` that are not enabled by default.
  142.   httpAgent: new http.Agent({ keepAlive: true }),
  143.   httpsAgent: new https.Agent({ keepAlive: true }),
  144.   // `proxy` defines the hostname, port, and protocol of the proxy server.
  145.   // You can also define your proxy using the conventional `http_proxy` and
  146.   // `https_proxy` environment variables. If you are using environment variables
  147.   // for your proxy configuration, you can also define a `no_proxy` environment
  148.   // variable as a comma-separated list of domains that should not be proxied.
  149.   // Use `false` to disable proxies, ignoring environment variables.
  150.   // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  151.   // supplies credentials.
  152.   // This will set an `Proxy-Authorization` header, overwriting any existing
  153.   // `Proxy-Authorization` custom headers you have set using `headers`.
  154.   // If the proxy server uses HTTPS, then you must set the protocol to `https`.
  155.   proxy: {
  156.     protocol: 'https',
  157.     host: '127.0.0.1',
  158.     // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
  159.     port: 9000,
  160.     auth: {
  161.       username: 'mikeymike',
  162.       password: 'rapunz3l'
  163.     }
  164.   },
  165.   // `cancelToken` specifies a cancel token that can be used to cancel the request
  166.   // (see Cancellation section below for details)
  167.   cancelToken: new CancelToken(function (cancel) {
  168.   }),
  169.   // an alternative way to cancel Axios requests using AbortController
  170.   signal: new AbortController().signal,
  171.   // `decompress` indicates whether or not the response body should be decompressed
  172.   // automatically. If set to `true` will also remove the 'content-encoding' header
  173.   // from the responses objects of all decompressed responses
  174.   // - Node only (XHR cannot turn off decompression)
  175.   decompress: true, // default
  176.   // `insecureHTTPParser` boolean.
  177.   // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
  178.   // This may allow interoperability with non-conformant HTTP implementations.
  179.   // Using the insecure parser should be avoided.
  180.   // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
  181.   // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
  182.   insecureHTTPParser: undefined, // default
  183.   // transitional options for backward compatibility that may be removed in the newer versions
  184.   transitional: {
  185.     // silent JSON parsing mode
  186.     // `true`  - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
  187.     // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
  188.     silentJSONParsing: true, // default value for the current Axios version
  189.     // try to parse the response string as JSON even if `responseType` is not 'json'
  190.     forcedJSONParsing: true,
  191.     // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
  192.     clarifyTimeoutError: false,
  193.   },
  194.   env: {
  195.     // The FormData class to be used to automatically serialize the payload into a FormData object
  196.     FormData: window?.FormData || global?.FormData
  197.   },
  198.   formSerializer: {
  199.       visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values
  200.       dots: boolean; // use dots instead of brackets format
  201.       metaTokens: boolean; // keep special endings like {} in parameter key
  202.       indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
  203.   },
  204.   // http adapter only (node.js)
  205.   maxRate: [
  206.     100 * 1024, // 100KB/s upload limit,
  207.     100 * 1024  // 100KB/s download limit
  208.   ]
  209. }
复制代码
其他Request method aliases

axios(url[,config]):可只指定url发送get请求
axios.requst(config) :等同于axios(config)
axios.get(url[, config]): 发 get 请求
axios.delete(url[, config]): 发 delete 请求
axios.post(url[, data, config]): 发 post 请求
axios.put(url[, data, config]): 发 put 请求
设置默认值

全局axios默认值

  1. axios.defaults.configOption = '';
  2. //axios.defaults.baseURL = 'http://localhost/3000';
复制代码
自定义实例默认值

  1. // 创建实例对象时设置默认值
  2. const instance = axios.create({
  3.   baseURL: 'https://api.example.com'
  4. });
  5. // 创建完毕时也能更改默认值
  6. instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
复制代码
自定义实例对象发请求

基本语法

  1. //const instanceName = axios.create([config])
  2. //创建实例对象,instance对象和axios对象几近一样
  3. const instance = axios.create({
  4.         baseURL = 'http://localhost/3000',
  5.         timeout = 3000,
  6.         headers:{'X-Custom-Header': 'foobar'}
  7. })
  8. //使用实例对象发请求,基本上instance对象能使用axios的所有API
  9. instance({
  10.         method:'get',
  11.         url:'/index',
  12.         data:{}
  13. })
复制代码
拦截器

请求拦截器和相应拦截器
You can intercept requests or responses before they are handled by or .then catch
  1. //设置请求拦截器
  2. axios.interceptors.request.use(function (config) {
  3.     // Do something before request is sent
  4.     return config;
  5.   }, function (error) {
  6.     // Do something with request error
  7.     return Promise.reject(error);
  8.   });
  9. // 设置响应拦截器
  10. axios.interceptors.response.use(function (response) {
  11.     // Any status code that lie within the range of 2xx cause this function to trigger
  12.     // Do something with response data
  13.     return response;
  14.   }, function (error) {
  15.     // Any status codes that falls outside the range of 2xx cause this function to trigger
  16.     // Do something with response error
  17.     return Promise.reject(error);
  18.   });
  19. //设置完之后再正常使用axios对象或者instance对象
  20. //若同一对象身上有多个请求拦截器,调用的顺序和代码顺序是相反的,也即后进先执行
  21. //若同一对象身上有多个响应拦截器,调用的顺序和代码顺序是相同的。
复制代码
axios取消请求

  1. //结构化的配置
  2. let cancel;
  3. axios.get('/user/12345', {
  4.   cancelToken: new axios.CancelToken(function executor(c) {
  5.     // An executor function receives a cancel function as a parameter
  6.     cancel = c;
  7.   })
  8. });
  9. // 调用函数关闭请求
  10. cancel();
复制代码
从 Axios v0.22.0开始,支持 AbortController 以 fetch API 的方式取消请求
  1. const controller = new AbortController();
  2. axios.get('/foo/bar', {
  3.    signal: controller.signal
  4. }).then(function(response) {
  5.    //...
  6. });
  7. // cancel the request
  8. controller.abort()
复制代码
本次分享先到这里,具体的一些理论,请看我下篇的axios源码分析…

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




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4