全栈的自我修养: 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. charles 破解方法

    1.https://www.charlesproxy.com/latest-release/download.do 官网下载charles 2.傻瓜式安装完成(路径可以默认c盘) 3.安装完成后去c盘 ...

  2. SpringBoot 构建 Docker 镜像的 3 种方式

    本文将介绍3种技术,通过 Maven 把 SpringBoot 应用构建成 Docker 镜像. (1)使用 spring-boot-maven-plugin 内置的 build-image. (2) ...

  3. Error: Cannot find module 'webpack'

    运行 npm start 报错 Error: Cannot find module 'webpack' 安装了 npm install --save-dev webpack cnpm install ...

  4. 35 _ 队列1 _ 什么是队列.swf

    队列是一种可以实现一个先进先出的存储结构 什么是队列? 队列(Queue)也是一种运算受限的线性表.它只允许在表的一端进行插入,而在另一端进行删除.允许删除的一端称为队头(front),允许插入的一端 ...

  5. 2、尚硅谷_SSM高级整合_创建Maven项目.avi

    第一步我们新建立一个web工程 这里首先要勾选上enable的第一个复选框 这里要勾选上add maven support 我们在pom.xml中添加sevlet的依赖 创建java web项目之后, ...

  6. 【Vim命令】

    命令 操作 :set nu 显示行号  i 编辑模式  :wq  修改并退出  :%s/a/b  把所有的a替换成b                        

  7. 4. union-find算法

    算法的主题思想: 1.优秀的算法因为能够解决实际问题而变得更为重要: 2.高效算法的代码也可以很简单: 3.理解某个实现的性能特点是一个挑战: 4.在解决同一个问题的多种算法之间进行选择时,科学方法是 ...

  8. JavaScript基础有关构造函数、new关键字和this关键字(009)

    1. 总是记得用new关键字来执行构造函数.前面提到,可以用构造函数创建JavaScript的对象,这个构造函数在使用的时候需要使用new关键字,但如果忘记写入new关键字,会怎么样?事实上这个函数还 ...

  9. 【必读】前端需要懂的 APP 容器原理

    App 容器,简言之,App 承载某类应用(H5/RN/Weex/小程序/Flutter ...)的运行环境,可主动干预并进行功能扩展,达到丰富能力.优化性能.提升体验的目的,如页面数据预取(pref ...

  10. Centos 6.4 安装KSnapshot 和gimp截图工具

    一. # wget http://www.ibiblio.org/pub/Linux/X11/xutils/ksnapshot-0.2.7.tar.gz # tar -zxvf ksnapshot-0 ...