Axios 那些事

456 阅读7分钟

后端返回的Number类型数据过长精度丢失

这种情况一般是因为后端使用了雪花算法导致的

原因:

js里面的整数有安全范围,即最大能显示的范围,超过了这个范围可能会精度丢失

// 控制台输入
console.log(1215831343376629760)
// 输出结果
1215831343376629800
// 对比数字
1215831343376629760
1215831343376629800 // 后面部分精度丢失了

解决方案

后端 将Number类型转化为String类型
前端 使用插件json-bigint在响应返回中拦截

设置请求头headers的问题

post请求自定义headers

axios.post('url', params,{
  headers: { 'Content-Type': 'application/octet-stream' },
}),

get请求
axios不允许get请求设置headers。当传入data时,可以设置成功。

axios.get('url', {
  params,
  data: {},
  headers: { 'Content-Type': 'application/octet-stream' },
}),

后端返回流数据,前端请求时需要设置responseType

post

axios.post('url', params,{
  responseType: 'blob',
}),

get

axios.get('url', { params,
  responseType: 'blob',
}),

后端返回的数据如下。蓝色为后端返回的数据格式 红色为前端传递的参数

image.png
上面的headers里面content-disposition携带有下载的文件的文件名

前端需要发送FormData格式数据给后端时

let formData = new FormData();
formData.append("name", '文件名'); // 只能通过append来添加参数
formData.append("file", '文件');
axios.post('url', formData,{
  'Content-Type': 'multipart/form-data' // 一般情况下都需要设置这个请求头
}),

基本讲解

get请求

axios.get('https://www.runoob.com/try/ajax/json_demo.json', {
        params: {
            name: 'jon'
        },
        // `headers` 是即将被发送的自定义请求头
        headers: { 
            "X-Requested-With": "XMLHttpRequest", 
            "Content-Type": "application/x-www-form-urlencoded",
        },
        // `responseType` 表示服务器响应的数据类型,可以是 "arraybuffer", "blob", "document", "json", "text", "stream"
        responseType: "json", // 默认的
    })

post请求

axios.post('https://www.runoob.com/try/ajax/json_demo.json', {
        data: {
            name: 'jon'
        },
        // `headers` 是即将被发送的自定义请求头
        headers: { 
            "X-Requested-With": "XMLHttpRequest", 
            "Content-Type": "application/x-www-form-urlencoded",
        },
        // `responseType` 表示服务器响应的数据类型,可以是 "arraybuffer", "blob", "document", "json", "text", "stream"
        responseType: "json", // 默认的
    })

config配置

axios#get(url[, config])
axios#post(url[, 数据[, 配置]])

{
  // `url` 是将用于请求的服务器 URL
  url: '/user',

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

  // 除非“url”是绝对的,否则“baseURL”将被添加到“url”之前。
  // 可以方便地为 axios 实例设置 `baseURL` 来传递相对 URL
  // to methods of that instance.
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` 允许在请求数据发送到服务器之前对其进行更改
  // 这仅适用于请求方法“PUT”、“POST”、“PATCH”和“DELETE”
  // 数组中的最后一个函数必须返回一个字符串或者一个 Buffer、ArrayBuffer、FormData 或 Stream 的实例
  // 您可以修改 headers 对象.
  transformRequest: [function (data, headers) {
    // 做任何你想做的事情来转换数据
    ...
    return data;
  }],

  // `transformResponse` 允许在将响应数据传递给 then/catch 之前对其进行更改
  transformResponse: [function (data) {
    // 做任何你想做的事情来转换数据
    ...
    return data;
  }],

  // `headers` 是要发送的自定义标头
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` 是要随请求发送的 URL 参数
  // 必须是普通对象或 URLSearchParams 对象
  params: {
    ID: 12345
  },
  
  // `paramsSerializer`是一个可选配置,允许您自定义序列化`params`. 
  paramsSerializer: {

    //Custom encoder function which sends key/value pairs in an iterative fashion.
    encode?: (param: string): string => { /* Do custom operations here and return transformed string */ }, 
    
    // Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour.
    serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), 
    
    //Configuration for formatting array indexes in the params. 
    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).    
  },

  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
  // When no `transformRequest` is set, must be of one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer, FormData (form-data package)
  data: {
    firstName: 'Fred'
  },

  // syntax alternative to send data into the body
  // method post
  // only the value is sent, not the key
  data: 'Country=Brasil&City=Belo Horizonte',

  // `timeout` specifies the number of milliseconds before the request times out.
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000, // default is `0` (no timeout)

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md)
  adapter: function (config) {
    /* ... */
  },
  // Also, you can set the name of the built-in adapter, or provide an array with their names
  // to choose the first available in the environment
  adapter: 'xhr' // 'fetch' | 'http' | ['xhr', 'http', 'fetch']

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  // Please note that only HTTP Basic auth is configurable through this parameter.
  // For Bearer tokens and such, use `Authorization` custom headers instead.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` indicates the type of data that the server will respond with
  // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
  //   browser only: 'blob'
  responseType: 'json', // default

  // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  // options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',
  // 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',
  // 'utf8', 'UTF8', 'utf16le', 'UTF16LE'
  responseEncoding: 'utf8', // default

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default
    
  // `undefined` (default) - set XSRF header only for the same origin requests
  withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),

  // `onUploadProgress` allows handling of progress events for uploads
  // browser & node.js
  onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
    // Do whatever you want with the Axios progress event
  },

  // `onDownloadProgress` allows handling of progress events for downloads
  // browser & node.js
  onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
    // Do whatever you want with the Axios progress event
  },

  // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
  maxContentLength: 2000,

  // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
  maxBodyLength: 2000,

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  maxRedirects: 21, // default

  // `beforeRedirect` defines a function that will be called before redirect.
  // Use this to adjust the request options upon redirecting,
  // to inspect the latest response headers,
  // or to cancel the request by throwing an error
  // If maxRedirects is set to 0, `beforeRedirect` is not used.
  beforeRedirect: (options, { headers }) => {
    if (options.hostname === "example.com") {
      options.auth = "user:password";
    }
  },

  // `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
  
  // `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.
  transport: undefined, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // `proxy` defines the hostname, port, and protocol of the proxy server.
  // You can also define your proxy using the conventional `http_proxy` and
  // `https_proxy` environment variables. If you are using environment variables
  // for your proxy configuration, you can also define a `no_proxy` environment
  // variable as a comma-separated list of domains that should not be proxied.
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  // If the proxy server uses HTTPS, then you must set the protocol to `https`.
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  }),

  // an alternative way to cancel Axios requests using AbortController
  signal: new AbortController().signal,

  // `decompress` indicates whether or not the response body should be decompressed
  // automatically. If set to `true` will also remove the 'content-encoding' header
  // from the responses objects of all decompressed responses
  // - Node only (XHR cannot turn off decompression)
  decompress: true, // default

  // `insecureHTTPParser` boolean.
  // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
  // This may allow interoperability with non-conformant HTTP implementations.
  // Using the insecure parser should be avoided.
  // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
  // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
  insecureHTTPParser: undefined, // default

  // transitional options for backward compatibility that may be removed in the newer versions
  transitional: {
    // silent JSON parsing mode
    // `true`  - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
    // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
    silentJSONParsing: true, // default value for the current Axios version

    // try to parse the response string as JSON even if `responseType` is not 'json'
    forcedJSONParsing: true,

    // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
    clarifyTimeoutError: false,
  },

  env: {
    // The FormData class to be used to automatically serialize the payload into a FormData object
    FormData: window?.FormData || global?.FormData
  },

  formSerializer: {
      visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values
      dots: boolean; // use dots instead of brackets format
      metaTokens: boolean; // keep special endings like {} in parameter key
      indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
  },

  // http adapter only (node.js)
  maxRate: [
    100 * 1024, // 100KB/s upload limit,
    100 * 1024  // 100KB/s download limit
  ]
}

欢迎大家留言讨论,合作共赢!