【Js】axios使用文档

总结了一份比较便于阅读,用于突然想不起如何调用时查阅。

【Js】axios使用文档

By img Microanswer Create at:Nov 14, 2019, 9:40:03 AM 

Tags: axios vue js javascript nodejs

总结了一份比较便于阅读,用于突然想不起如何调用时查阅。


axios是一款js中使用的http请求工具,受到许多开发者的青睐。本文记录了此工具的常用文档。以便于以后快速查阅。

一、简介与安装

axios帮我们封装了许多常用功能,在正式使用前,先看看如何安装吧。

1、用于html页面

直接在你的html页面里面加入:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

即可在你的网页script节点里使用axios进行网络请求了。

2、用于nodejs

如果是使用nodejs环境,直接使用命令:

npm i axios --save

就可以完成安装。安装完成后,希望在哪一个模块里使用,就只需要:

const axios = require("axios");

二、常用方法

axios 提供了多种方式让你可以调用其方法,可以说无死角都是方法。

1、GET请求

axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

2、POST请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

3、直接使用axios

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

4、使用axios.request

这个其实和使用 axios 是一样的,只是多了一个request单词,感觉更有那个意思。

axios.request({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

三、常用API

// [] 中括号表示此参数可选。
axios#create(config)
axios#request(config)
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]])
axios#getUri([config])

四、axios.create

通过此方法可以创建一个axios对象,使用创建的对象同样可以按照本文档使用。要注意,axios 本身也是一个axios对象,它是一个全局的,当你使用create方法创建了新的对象时,此新的对象可能配置和全局对象本身有配置上的差异,从而体现出行为上的差异。

五、对象属性

1、Config对象

在使用axios过程中会传递基本会一个 config 配置对象,此配置对象支持一下参数:

{
  // `url` 要请求的地址
  url: '/user',
 
  // `method` 请求方式
  method: 'get', // default
 
  // `baseURL` 可以在创建axios对象时使用此配置,用于配置指定url的前缀路径。
  baseURL: 'https://some-domain.com/api/',
 
  // `transformRequest` 此配置相当于一个拦截器,允许你在请求前对数据进行处理。此值是一个数组,可以配置对个方法,但必须在数组最后一个方法返回data,否则将不会发送数据到服务端。此方法对于GET类的请求无效。因为GEt没有请求体。
  transformRequest: [function (data, headers) {
    return data;
  }],
 
  // `transformResponse` 此方法相当于一个拦截器,用于收到响应后你可以处理一下响应结果。此配置是一个数组,你必须在最后一个方法里返回data,否则你在then里面得到的响应不是你预期的响应。
  transformResponse: [function (data) {
    return data;
  }],
 
  // `headers` 允许你传入一个你自己的head配置。
  headers: {'X-Requested-With': 'XMLHttpRequest'},
 
  // `params` 用于放在url上的参数请求。
  params: {
    ID: 12345
  },
 
  // `paramsSerializer` 将param参数放在url上是,使用的序列化方法。此配置可选。
  paramsSerializer: function (params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },
 
  // `data` 要通过POST、PUT等方法支持请求体的,此配置则指定要传送的请求体。允许下面的类型的值:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器还支持: FormData, File, Blob
  // - Nodejs环境还支持: Stream, Buffer
  data: {
    firstName: 'Fred'
  },
 
  // `timeout` 请求超时时间
  timeout: 1000, // 默认 0 (不超时)
 
  // `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) {
    /* ... */
  },
 
  // `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
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  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
 
  // `onUploadProgress` allows handling of progress events for uploads
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },
 
  // `onDownloadProgress` allows handling of progress events for downloads
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },
 
  // `maxContentLength` defines the max size of the http response content in bytes allowed
  maxContentLength: 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: 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` 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 and port 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`.
  proxy: {
    host: '127.0.0.1',
    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) {
  })
}

2、使用默认配置

你可以通过 defaults 为某实例设定默认配置。

// axios 本身也是一个 axios 实例,所以可以直接这样设置全局配置。
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 同时你也可以同样的方法设置其它axios实例的默认配置,这样允许你在创建实例后重新设置默认配置。
var instance = axios.create({
  baseURL: 'https://api.example.com'
});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

3、响应Response对象

{
  // `data` 服务端返回的数据
  data: {},
 
  // `status` 状态码
  status: 200,
 
  // `statusText` 状态文案
  statusText: 'OK',
 
  // `headers` 响应头
  headers: {},
 
  // `config` 请求时指定的配置
  config: {},
 
  // `request` 产生本次响应的请求。
  request: {}
}
Full text complete, Reproduction please indicate the source. Help you? Not as good as one:
Comment(Comments need to be logged in. You are not logged in.)
You need to log in before you can comment.

Comments (2 Comments)