全栈的自我修养: 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. java 拦截器解决xss攻击

    一.xss攻击 XSS攻击通常指的是通过利用网页开发时留下的漏洞,通过巧妙的方法注入恶意指令代码到网页,使用户加载并执行攻击者恶意制造的网页程序.这些恶意网页程序通常是JavaScript,但实际上也 ...

  2. cb49a_c++_STL_算法_对所有元素排序_sort_stable_sort

    cb49a_c++_STL_算法_对所有元素排序_sort_stable_sort sort(b,e) sort(b,e,p) stable_sort(b,e) stable_sort(b,e,p) ...

  3. Jenkins项目构建运行

    [准备环境] 继Jenkins环境搭建完成后,进行插件的管理 [思路] 项目顺序是,开发提交代码到代码仓库,测试通过Jenkins拉下开发的代码打包部署: 1.开发提交代码 2.Jenkins自动从代 ...

  4. docker安装mysql,设置mysql初始密码

    docker安装mysql,只需要2分钟就可以完成 docker search mysql 拉取mysql镜像(https://hub.docker.com/_/mysql) docker pull ...

  5. v-model指令的学习(双向绑定)

    v-bind 只能实现数据的单项绑定,从data到view,无法实现双向绑定 v-model可以实现表单元素和model中数据的双向绑定 注意:model只能运用到表单元素中 如:input sele ...

  6. 流媒体学习计划表——pr

    参考教程 视频:b站oeasy 书籍:<adobe premiere pro cc 2018经典教程> 学习教训 一定要多做--实践是检验真理的唯一标准 书籍补充理论知识,视频讲究实操(理 ...

  7. 数据库char varchar nchar nvarchar,编码Unicode,UTF8,GBK等,Sql语句中文前为什么加N(一次线上数据存储乱码排查)

    背景 公司有一个数据处理线,上面的数据经过不同环境处理,然后上线到正式库.其中一个环节需要将数据进行处理然后导入到另外一个库(Sql Server).这个处理的程序是老大用python写的,处理完后进 ...

  8. Git的常用命令记录

    Git的常用命令记录 1.与远程仓库建立连接,即关联一个远程库 git remote add origin git@server-name:path/repo-name.git; 2.查看当前分支  ...

  9. 基于 Blazor 开发五子棋⚫⚪小游戏

    今天是农历五月初五,端午节.在此,祝大家端午安康! 端午节是中华民族古老的传统节日之一.端午也称端五,端阳.此外,端午节还有许多别称,如:午日节.重五节.五月节.浴兰节.女儿节.天中节.地腊.诗人节. ...

  10. 腾讯IEG--2020春招实习

    笔试 正常批就五道编程题,可以跳出使用本地IDE,题目很好理解,基本都能写出来,但是要过全部用例不容易.具体题目和题解可以看看这位大佬的牛客帖子,我的就不献丑了,有两题都只过了40%,我当时是用C#做 ...