全栈的自我修养: Axios 的简单使用

You should never judge something you don't understand.

你不应该去评判你不了解的事物。

全栈的自我修养: 001环境搭建 (使用Vue,Spring Boot,Flask,Django 完成Vue前后端分离开发)

全栈的自我修养: 002使用@vue/cli进行vue.js环境搭建 (使用Vue,Spring Boot,Flask,Django 完成Vue前后端分离开发)

全栈的自我修养: 003Axios 的简单使用

@

介绍

Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中。

Github开源地址: https://github.com/axios/axios

如果你原来用过 jQuery 应该还记的 $.ajax 方法吧

简单使用

如果按照HTTP方法的语义来暴露资源,那么接口将会拥有安全性和幂等性的特性,例如GET和HEAD请求都是安全的, 无论请求多少次,都不会改变服务器状态。而GET、HEAD、PUT和DELETE请求都是幂等的,无论对资源操作多少次, 结果总是一样的,后面的请求并不会产生比第一次更多的影响。

下面列出了 GETDELETEPUT, PATCHPOST 的典型用法:

GET

axios#get(url[, config])

从方法声明可以看出

  1. 第一个参数url必填,为请求的url
  2. 第二个参数 config 选填, 关于config 的属性见下文

GET 方法用来查询服务资源, 不应该在这里对服务资源进行修改

  1. 使用get 方法进行请求,参数可以直接拼接在 url 中
axios.get('/user?id=12345')
.then(response => {
// 如果成功返回(http 状态码在 200~300),则可获取对应的 response
console.log(response);
})
.catch(error => {
// 异常
console.log(error);
})
.then(() => {
// always executed
});
  1. 使用get 方法进行请求,参数单独作为一个对象传入, 该参数会拼接在url 中

let request_params = { id: 123456 } axios.get('/user', {
params: request_params
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});

DELETE

axios#delete(url[, config])

从方法声明可以看出

  1. 第一个参数url必填,为请求的url
  2. 第二个参数 config 选填, 关于config 的属性见下文

DELETE 用来删除一个资源,不安全但幂等

  1. 使用 DELETE 方法进行请求,参数可以直接拼接在 url 中
axios.delete('/user?id=12345')
.then(response => {
// 如果成功返回(http 状态码在 200~300),则可获取对应的 response
console.log(response);
})
.catch(error => {
// 异常
console.log(error);
})
.then(() => {
// always executed
});
  1. 使用 DELETE 方法进行请求,参数单独作为一个对象传入, 该参数会拼接在url 中

let request_params = { id: 123456 } axios.delete('/user', {
params: request_params
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
  1. 使用 DELETE 方法进行请求,参数单独作为一个对象传入, 该参数会在请求体中

let request_params = { id: 123456 } axios.delete('/user', {
data: request_params
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});

PUT

axios#put(url[, data[, config]])

从方法声明可以看出

  1. 第一个参数url必填,为请求的url
  2. 第二个参数data选填,为请求的参数,且在请求体中
  3. 第二个参数 config 选填, 关于config 的属性见下文
  1. 不安全但幂等
  2. 通过替换的方式更新资源

常见使用方式

  1. 使用 PUT 方法进行请求,参数可以直接拼接在 url 中

更新资源

axios.put('/user?id=12345&name=abc')
.then(response => {
// 如果成功返回(http 状态码在 200~300),则可获取对应的 response
console.log(response);
})
.catch(error => {
// 异常
console.log(error);
})
.then(() => {
// always executed
});
  1. 使用 PUT 方法进行请求,参数单独作为一个对象传入, 该参数会在请求体中

let request_params = { id: 123456, name: "abc" } axios.post('/user', request_params,
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});

POST

axios#post(url[, data[, config]])

从方法声明可以看出

  1. 第一个参数url必填,为请求的url
  2. 第二个参数data选填,为请求的参数,且在请求体中
  3. 第二个参数 config 选填, 关于config 的属性见下文
  1. 不安全且不幂等
  2. 创建资源

常见使用方式

  1. 使用 POST 方法进行请求,参数可以直接拼接在 url 中

创建id为123456的用户

axios.post('/user?id=12345&name=abc')
.then(response => {
// 如果成功返回(http 状态码在 200~300),则可获取对应的 response
console.log(response);
})
.catch(error => {
// 异常
console.log(error);
})
.then(() => {
// always executed
});
  1. 使用 POST 方法进行请求,参数单独作为一个对象传入, 该参数会在请求体中

let request_params = { id: 123456, name: "abc" } axios.post('/user', request_params,
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});

PATCH

axios.patch(url[, data[, config]])

从方法声明可以看出

  1. 第一个参数url必填,为请求的url
  2. 第二个参数data选填,为请求的参数,且在请求体中
  3. 第二个参数 config 选填, 关于config 的属性见下文
  1. 不安全且不幂等
  2. 在服务器更新资源(客户端提供改变的属性,部分更新)

常见使用方式

  1. 使用 PATCH 方法进行请求,参数可以直接拼接在 url 中

更新id为123456的用户资源

axios.patch('/user?id=12345&name=abc')
.then(response => {
// 如果成功返回(http 状态码在 200~300),则可获取对应的 response
console.log(response);
})
.catch(error => {
// 异常
console.log(error);
})
.then(() => {
// always executed
});
  1. 使用 PATCH 方法进行请求,参数单独作为一个对象传入, 该参数会在请求体中

let request_params = { id: 123456, name: "abc" } axios.patch('/user', request_params,
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});

汇总

从上面的示例中可以看出

axios.get(url[, config])
axios.delete(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

其中 POSTPUTPATCH 的使用方式是一致的,只是方式名http method 存在差异, 那他们的区别在什么地方呢

GET:从服务器取出资源(一项或多项)。
POST:在服务器新建一个资源。
PUT:在服务器更新资源(客户端提供改变后的完整资源)。
PATCH:在服务器更新资源(客户端提供改变的属性)。
DELETE:从服务器删除资源。

使用 application/x-www-form-urlencoded

在默认情况下,data 中数据采用了 JSON 序列化方式,即 Content-Type: application/json, 如果想使用 application/x-www-form-urlencoded, 则需要做特殊处理

方式一:使用 URLSearchParams

const params = new URLSearchParams();
params.append('id', '123456');
params.append('name', 'abc');
axios.post('/user', params);

其中 URLSearchParams 存在兼容问题,具体可见caniuse

方式二:使用 qs 进行编码

import qs from 'qs';
axios.post('/user', qs.stringify({ id: 123456, name: "abc" }));

使用 multipart/form-data

const form = new FormData();
form.append('id', 123456);
form.append('name', "abc"); axios.post('user', form, { headers: form.getHeaders() })

Response 结构

{
// `data` is the response that was provided by the server
// response 返回数据
data: {}, // `status` is the HTTP status code from the server response
// 状态码
status: 200, // `statusText` is the HTTP status message from the server response
// 状态码对应的标准message
statusText: 'OK', // `headers` the HTTP headers that the server responded with
// All header names are lower cased and can be accessed using the bracket notation.
// Example: `response.headers['content-type']`
// 响应头
headers: {}, // `config` is the config that was provided to `axios` for the request
config: {}, // `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
}

Config 常用配置

{
// `url` is the server URL that will be used for the request
url: '/user', // `method` is the request method to be used when making the request
method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute.
// 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/', // `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
// 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;
}], // `headers` are custom headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params: {
ID: 12345
}, // `paramsSerializer` is an optional function in charge of serializing `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` 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
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 // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
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
responseEncoding: 'utf8', // default // `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
},
}

更多配置参考 https://github.com/axios/axios

参考

  1. https://github.com/axios/axios

全栈的自我修养: 003Axios 的简单使用的更多相关文章

  1. 全栈的自我修养: 001环境搭建 (使用Vue,Spring Boot,Flask,Django 完成Vue前后端分离开发)

    全栈的自我修养: 环境搭建 Not all those who wander are lost. 彷徨者并非都迷失方向. Table of Contents @ 目录 前言 环境准备 nodejs v ...

  2. 全栈的自我修养: 0005 Java 包扫描实现和应用(Jar篇)

    全栈的自我修养: 0005 Java 包扫描实现和应用(Jar篇) It's not the altitude, it's the attitude. 决定一切的不是高度而是态度. Table of ...

  3. 老男孩Python全栈第2期+课件笔记【高清完整92天整套视频教程】

    点击了解更多Python课程>>> 老男孩Python全栈第2期+课件笔记[高清完整92天整套视频教程] 课程目录 ├─day01-python 全栈开发-基础篇 │ 01 pyth ...

  4. 基于 Serverless Component 全栈解决方案

    什么是 Serverless Component Serverless Component 是 Serverless Framework 的,支持多个云资源编排和组织的场景化解决方案. Serverl ...

  5. 《web全栈工程师的自我修养》读书笔记

    有幸读了yuguo<web全栈工程师的自我修养>,颇有收获,故在此对读到的内容加以整理,方便指导,同时再回顾一遍书中的内容. 概览 整本书叙述的是作者的成长经历,通过经验的分享,给新人或者 ...

  6. web性能优化 来自《web全栈工程师的自我修养》

    最近在看<web全栈工程师的自我修养>一书,作者是来自腾讯的前端工程师.作者在做招聘前端的时候问应聘者web新能优化有什么了解和经验,应聘者思索后回答“在发布项目之前压缩css和 Java ...

  7. 《Web全栈工程师的自我修养》读书笔记(转载)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/5 ...

  8. 《web全栈工程师的自我修养》阅读笔记

    在买之前以为这本书是教你怎么去做一个web全栈工程师,以及介绍需要掌握的哪些技术的书,然而看的过程中才发现,是一本方法论的书.读起来的感觉有点像红衣教主的<我的互联网方法论>,以一些自己的 ...

  9. Web全栈工程师修养

    全栈工程师现在是个很热的话题,如何定义全栈工程师?在著名的问答网站Quora上有人提出了这个问题,其中一个获得了高票的回答是: 全栈工程师是指,一个能处理数据库.服务器.系统工程和客户端的所有工作的工 ...

随机推荐

  1. C++中为什么按两次ctrl+D才能结束标准I/O

    参考资料: https://www.douban.com/group/topic/127062773/ 今天学习了C++语言的标准I/O,也就是std::cin和std::cout,但是我发现当系统在 ...

  2. VScode快捷键集锦(持续更新)

    本文的快捷键是根据VScode for mac来的,Windows和Linux用户可能需要些许改动. 注释:cmd + /  注释当前选中的行,或者注释掉选中的行,再按一次反注释.还可以在按cmd + ...

  3. 如何开发一个自己的npm包

    目录 一.初始化npm包 二.新建自己的工具类 三.新建入口文件index.js 四.编写单元测试 五.登录仓库 六.发布包 七.安装使用 八.删除包 一.初始化npm包 npm init 运行输入包 ...

  4. Python3-算法-递归

    递归 递归算法是指一般通过函数或子进程来实现,在函数或子进程的内部,直接或间接地调用自己的算法,说白了就是自己调自己 注: 1.在使用递归的时候,必须要有一个递归出口,即一个明确的结束条件,否则就是死 ...

  5. python 3内置函数

    2018-07-14 enumerate() 用于指定下标 例: m = ['a','b','c'] for i,j in enumerate(m,1): print(i,j) 输出: 1 a 2 b ...

  6. 并发04--JAVA中的锁

    1.Lock接口 Lock与Synchronized实现效果一致,通过获得锁.释放锁等操作来控制多个线程访问共享资源,但是Synchronized将获取锁固话,必须先获得锁,再执行,因此两者对比来说, ...

  7. could not resolve property(无法解析属性)

    could not resolve property(无法解析属性) 顾名思义在写hql语句的时候,属性写错了! 请检查大小写,是实体类的,不是数据库表的! 一个一个检查,仔细看!

  8. HDU 2157 How many ways?【矩阵快速幂】

    题目 春天到了, HDU校园里开满了花, 姹紫嫣红, 非常美丽. 葱头是个爱花的人, 看着校花校草竞相开放, 漫步校园, 心情也变得舒畅. 为了多看看这迷人的校园, 葱头决定, 每次上课都走不同的路线 ...

  9. 深入理解JavaScript系列(2):揭秘命名函数表达式(转)

    前言 网上还没用发现有人对命名函数表达式进去重复深入的讨论,正因为如此,网上出现了各种各样的误解,本文将从原理和实践两个方面来探讨JavaScript关于命名函数表达式的优缺点. 简 单的说,命名函数 ...

  10. 09 . Prometheus监控tomcat+jvm

    List CentOS7.3 prometheus-2.2.1.linux-amd64.tar.gz redis_exporter-v0.30.0.linux-amd64.tar.gz 节点名 IP ...