JavaScript HTTP客户端库axios介绍

简介: HTTP客户端是很多时候我们都需要用到的功能,今天就来介绍一个比较流行的JavaScript编写的HTTP客户端库axios。安装如果你会使用npm的话,可以使用npm来装,非常方便。

HTTP客户端是很多时候我们都需要用到的功能,今天就来介绍一个比较流行的JavaScript编写的HTTP客户端库axios

安装

如果你会使用npm的话,可以使用npm来装,非常方便。

$ npm install axios

如果你准备在浏览器中尝试使用,可以直接使用CDN。

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

快速上手

在使用axios之前,先来介绍一下ES6标准中引入的Promise对象,它是为了方便异步编程而设立的。如果希望详细了解Promise对象的用法,可以查看这里。Promise对象含有thencatch方法,分别用来处理异步操作和抛出异常操作。所以如果一个方法返回Promise对象,我们就可以简单的像这样编写异步操作。

funtionReturnPromise(XXX)
    .then(function (returnValue) {
    //异步操作
    })
    .catch(function (error) {
    //异常处理
    })

HTTPBIN这个网站可以帮助我们测试HTTP请求, 所以这里使用它作为目标网站。

GET请求

axios.get('http://httpbin.org/get?fuck=shit')
    .then(function (response) {
        console.log(response.data)
    })
    .catch(function (error) {
        console.log(error)
    })

当然请求参数也可以单独传进去。

axios.get('http://httpbin.org/get', {
    params: {
        fuck: "shit"
    }
})
    .then(function (response) {
        console.log(response.data)
    })
    .catch(function (error) {
        console.log(error)
    })

POST请求

POST请求的参数只能以参数的形式传入。

axios.post('http://httpbin.org/post', {
    fuck: 'shit',
    son: 'bitch'
})
    .then(function (response) {
        console.log(response.data)
    })
    .catch(function (error) {
        console.log(error)
    })

API介绍

使用配置发送请求

除了前面显式使用对应方法来发起请求,我们还可以使用配置来设置如何发送请求。例如,要发送一个POST请求,可以这么写。

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

所有请求方法

axios可以发送不同类型的HTTP请求,这些请求方法可以参考下面。

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.create([config])方法。下面创建了一个实例,然后用该实例发起请求。

let instance = axios.create({
    baseURL: 'https://httpbin.org/',
    timeout: 4000
})
instance.get('ip')
    .then(function (response) {
        console.log(response.data)
    })
    .catch(function (error) {
        console.log(error)
    })

实例上还有其他方法,基本和axios全局对象上的方法类似。

请求配置

前面很多地方已经使用了配置对象。下面来详细介绍一下该对象。

{
  // 请求地址
  url: '/user',

  // 请求方法类型
  method: 'get', // default

  // 基地址会和URL组合在一起,除非URL是绝对地址
  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  // to methods of that instance.
  baseURL: 'https://some-domain.com/api/',

  // 该方法可以按照自己的需求将响应转换成需要的格式
  // This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // http头
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // 请求参数,会添加到URL上
  // Must be a plain object or a URLSearchParams object
  params: {
    ID: 12345
  },

  // `paramsSerializer` 可以按照需要序列化参数
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` 参数会以请求体的形式进行发送
  // Only applicable for request methods 'PUT', 'POST', 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
  data: {
    firstName: 'Fred'
  },

  // `timeout` 指定超时毫秒数
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000,

  // `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`.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` indicates the type of data that the server will respond with
  // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // 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 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

  // `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' 指定请求使用的网络代理
  // 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` 指定取消token,这个token可以用来取消请求
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  })
}

响应对象

然后来介绍一下响应对象,也就是前面那些方法返回的response。

{
  // `data` 请求返回的数据(HTML、JSON等)
  data: {},

  // `status` 状态码
  status: 200,

  // `statusText` 状态文本
  statusText: 'OK',

  // `headers` 响应头
  // All header names are lower cased
  headers: {},

  // `config` axios请求使用的配置
  config: {},

  // `request` 产生这个响应的请求对象
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

取消请求

如果一个HTTP请求时间过长,可以取笑它。取消的使用方法如下。

let cancelToken = axios.CancelToken
let source = cancelToken.source()
axios.get('https://httpbin.org/ip', {
    cancelToken: source.token
})
    .then(function (response) {
        console.log(response.data)
    })
    .catch(function (error) {
        console.log(error)
    })
source.cancel('取消了HTTP请求')

使用application/x-www-form-urlencoded格式

默认情况下,axios会将JavaScript对象序列化为JSON对象,如果需要用application/x-www-form-urlencoded形式传送数据,可以使用下面的方法。

如果在浏览器中,可以使用URLSearchParams对象。

var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

如果在Node环境下,可以使用qs库。

var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));

一个简单的小例子

最后,照例用一个小例子结束。这是一个HTML文件,将它保存,然后在浏览器中打开即可。为了简单起见,这里使用原生的JavaScript操作,用到的第三方库只有axios一个。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>主页</title>
</head>
<body>
<h1>IP地址查询</h1>

<button onclick="onClick()">点击查询IP地址</button>
<h2 id="ip"></h2>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    function onClick() {
        axios.get('https://httpbin.org/ip')
            .then(function (response) {
                let ip = document.getElementById('ip')
                ip.textContent = response.data.origin
            })
            .catch(function (error) {
                alert(error)
            })
    }
</script>
</body>
</html>
相关文章
|
2月前
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
241 29
|
8月前
|
JavaScript 前端开发 API
网络请求库 – axios库
网络请求库 – axios库
267 60
|
7月前
使用Netty实现文件传输的HTTP服务器和客户端
本文通过详细的代码示例,展示了如何使用Netty框架实现一个文件传输的HTTP服务器和客户端,包括服务端的文件处理和客户端的文件请求与接收。
166 1
使用Netty实现文件传输的HTTP服务器和客户端
|
8月前
|
JSON 资源调度 JavaScript
Vue框架中Ajax请求的实现方式:使用axios库或fetch API
选择 `axios`还是 `fetch`取决于项目需求和个人偏好。`axios`提供了更丰富的API和更灵活的错误处理方式,适用于需要复杂请求配置的场景。而 `fetch`作为现代浏览器的原生API,使用起来更为简洁,但在旧浏览器兼容性和某些高级特性上可能略显不足。无论选择哪种方式,它们都能有效地在Vue应用中实现Ajax请求的功能。
173 4
|
9月前
|
开发者 Python
深入解析Python `httpx`源码,探索现代HTTP客户端的秘密!
深入解析Python `httpx`源码,探索现代HTTP客户端的秘密!
171 1
|
9月前
|
移动开发 JavaScript 前端开发
"解锁axios GET请求新姿势!揭秘如何将数组参数华丽变身,让你的HTTP请求在云端翩翩起舞,挑战技术极限!"
【8月更文挑战第20天】二维码在移动应用中无处不在。本文详述了在UniApp H5项目中实现二维码生成与扫描的方法。通过对比插件`uni-app-qrcode`和库`qrcode-generator`生成二维码,以及使用插件和HTML5 API进行扫描,帮助开发者挑选最佳方案。无论是即插即用的插件还是灵活的JavaScript实现,都能满足不同需求。
73 0
|
10月前
|
XML 前端开发 JavaScript
JavaEE:http请求 | 过滤器 | 同步与异步请求 | 跨域问题 | axios框架 有这一篇就够!
JavaEE:http请求 | 过滤器 | 同步与异步请求 | 跨域问题 | axios框架 有这一篇就够!
|
10月前
|
Go 开发者
golang的http客户端封装
golang的http客户端封装
231 0
|
10月前
|
存储 资源调度 前端开发
JavaScript 使用axios库发送 post请求给后端, 给定base64格式的字符串数据和一些其他参数, 使用表单方式提交, 并使用onUploadProgress显示进度
使用 Axios 发送包含 Base64 数据和其他参数的 POST 请求时,可以通过 `onUploadProgress` 监听上传进度。由于整个请求体被视为一个单元,所以进度可能不够精确,但可以模拟进度反馈。前端示例代码展示如何创建一个包含 Base64 图片数据和额外参数的 `FormData` 对象,并在上传时更新进度条。后端使用如 Express 和 Multer 可处理 Base64 数据。注意,实际进度可能不如文件上传精确,显示简单加载状态可能更合适。
|
11月前
|
数据采集 Java API
Java HTTP客户端工具的演变之路
Java HTTP客户端工具的演变之路