全栈的自我修养: 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. FR嵌套报表(Nested Report)

    //主界面只是说明放置了哪些东西(3个ADOQuery不必放): //MasterSource.MasterField的设置如下: 1) Customer.Orders.Items 的 MasterS ...

  2. 其他函数-web_get_int_property

    用于记录http响应的信息.这个函数在调试脚本的常用,但是在实际压力测试中请将这些注释 使用这个函数可以获取到的信息有: 1.HTTP_INFO_RETURN_CODE:返回HTTP响应码 2.HTT ...

  3. Spring:BeanDefinition&PostProcessor不了解一下吗?

    水稻:这两天看了BeanDefinition和BeanFactoryPostProcessor还有BeanPostProcessor的源码.要不要了解一下 菜瓜:six six six,大佬请讲 水稻 ...

  4. linear-gradient,radial-gradient 渐变

    一.渐变效果 ->  线性渐变 方法: background-image: linear-gradient(direction, color-stop1, color-stop2, ...); ...

  5. Win10 1903小白搭建Redis

    一.Redis介绍 Please Baidu. 二.安装 1)下载: 下载网址 https://github.com/microsoftarchive/redis/releases 选这个 2)安装 ...

  6. 一文搞定Redis五大数据类型及应用场景

    本文学习知识点 redis五大数据类型数据类型:string.hash.list.set.sorted_set 五大类型各自的应用场景 @TOC 1. string类型 1-1 string类型数据的 ...

  7. MySQL的使用方法和视图、索引、以及存储过程的一些简单方法

    一,基本概念 1, 常用的两种引擎:         (1) InnoDB        a,支持ACID,简单地说就是支持事务完整性.一致性:         b,支持行锁,以及类似ORACLE的一 ...

  8. DNS bind使用

    概念介绍 DNS的分类 主DNS:配置管理,不提供服务,只用来编辑配置信息,给从DNS提供同步数据 从DNS:从主DNS上同步数据信息,对外提供服务 缓存DNS:在主DNS和从DNS之间,用来递归解析 ...

  9. Domain Adaptive Faster R-CNN:经典域自适应目标检测算法,解决现实中痛点,代码开源 | CVPR2018

    论文从理论的角度出发,对目标检测的域自适应问题进行了深入的研究,基于H-divergence的对抗训练提出了DA Faster R-CNN,从图片级和实例级两种角度进行域对齐,并且加入一致性正则化来学 ...

  10. 一条update SQL语句是如何执行的

    一条更新语句的执行过程和查询语句类似,更新的流程涉及两个日志:redo log(重做日志)和binlog(归档日志).比如我们要将ID(主键)=2这一行的值加(c:字段)1,SQL语句如下: upda ...