玄子Share-Axios 零基础到手撕源码

玄子Share-Axios 零基础到手撕源码

Axios 简介

Axios 是一个基于promise网络请求库,作用于node.js和浏览器中。 它是isomorphic的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.jshttp模块, 而在客户端 (浏览端) 则使用XMLHttpRequests

Axios 入门

使用方式

使用npm

$ npm install axios

1

使用CDN

1

模拟数据

官网:typicode https://github.com/typicode/json-server

安装 JSON 服务

npm install -g json-server

1

创建包含数据的db.json文件

{

"posts": [

{ "id": 1, "title": "json-server", "author": "typicode" }

],

"comments": [

{ "id": 1, "body": "some comment", "postId": 1 }

],

"profile": { "name": "typicode" }

}

1

2

3

4

5

6

7

8

9

启动 JSON 服务

json-server --watch db.json

1

请求http://localhost:3000/posts/1

{ "id": 1, "title": "json-server", "author": "typicode" }

1

关于更多描述以及路由请求见官网

Axios API

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.postForm(url[, data[, config]])

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

axios.patchForm(url[, data[, config]])
Title

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

Axios 实战

发送请求
Title

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

响应结构

一个请求的响应包含以下信息

{

// data 由服务器提供的响应

data: {},

// status 来自服务器响应的 HTTP 状态码

status: 200,

// statusText 来自服务器响应的 HTTP 状态信息

statusText: 'OK',

// headers 是服务器响应头

// 所有的 header 名称都是小写,而且可以使用方括号语法访问

// 例如: response.headers['content-type']

headers: {},

// configaxios 请求的配置信息

config: {},

// request 是生成此响应的请求

// 在node.js中它是最后一个ClientRequest实例 (in redirects),

// 在浏览器中则是 XMLHttpRequest 实例

request: {}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

并发请求
Title

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

相关推荐
软件开发技术深度爱好者2 天前
HTML5+CSS+JavaScript剪子石头布游戏
javascript·css·html5
小美元2 天前
echarts实现3D柱状图(视觉层面)根据博主改编
html5
惜.己2 天前
CSS样式基础样式选择器(案例+代码实现+效果图)
开发语言·前端·css·vscode·html·html5
码农幻想梦3 天前
html5 + css3(上)
前端·css3·html5
xcLeigh3 天前
HTML5实现好看的唐朝服饰网站模板源码2
前端·html·html5
samroom3 天前
前端学习第一天笔记 HTML5 CSS初学以及VSCODE中的常用快捷键
前端·css·笔记·学习·html5
码农幻想梦4 天前
html5 + css3(下)
前端·css3·html5
难搞靓仔4 天前
在VSCode中编写Html
vscode·html·html5
安冬的码畜日常4 天前
【CSS in Depth 2 精译_041】6.4 CSS 中的堆叠上下文与 z-index(上)
前端·css·css3·html5·css定位·z-index·元素堆叠
余生H4 天前
拿下奇怪的前端报错:某些多摄手机拉取部分摄像头视频流会导致应用崩溃,该如何改善呢?
前端·javascript·webrtc·html5·webview·相机