【axios】使用json-server 搭建REST API - 使用axios - 自定义axios - 取消请求 - 拦截器

1. 自己创建一个API

1.1 API 的分类

  1. REST API: restful (Representational State Transfer (资源)表现层状态转化)
    (1) 发送请求进行CRUD 哪个操作由请求方式来决定
    (2) 同一个请求路径可以进行多个操作
    (3) 请求方式会用到GET/POST/PUT/DELETE
  2. 非REST API: restless
    (1) 请求方式不决定请求的CRUD 操作
    (2) 一个请求路径只对应一个操作
    (3) 一般只有GET/POST

1.2 使用json-server 搭建REST API

1.2.1 json-server 是什么?

用来快速搭建REST API 的工具包

1.2.2 使用json-server

  1. 在线文档: https://github.com/typicode/json-server
  2. 下载: npm install -g json-server
  3. 目标根目录下创建数据库 json 文件: db.json
{
   
	"posts": [
		{
    "id": 1, "title": "json-server", "author": "typicode" },
		{
    "id": 2, "title": "json-server2", "author": "typicode" }
	],
	"comments": [
		{
    "id": 1, "body": "some comment", "postId": 1 }
	],
	"profile": {
    "name": "typicode" }
}
  1. 启动服务器执行命令: json-server --watch db.json

1.2.3 使用浏览器访问测试

http://localhost:3000/posts
http://localhost:3000/posts/1

1.2.4 使用axios 访问测试

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div>
    <button onclick="testGet()">GET请求</button>
    <button onclick="testPost()">POST请求</button>
    <button onclick="testPut()">PUT请求</button>
    <button onclick="testDelete()">DELETE请求</button>
  </div>

  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
  <script>
    function testGet() {
    
      axios.get('http://localhost:3000/posts') // 返回一个数组,数组里有两个对象
      // axios.get('http://localhost:3000/posts/1') // 返回一个对象
      // axios.get('http://localhost:3000/posts?id=1') // 返回一个数组,数组里有一个对象
      .then(response => {
    
        console.log('/posts get', response.data)
      })
    }

    function testPost() {
     // 添加数据
      axios.post('http://localhost:3000/posts', {
    "title": "json-server3", "author": "typicode" })
      .then(response => {
    
        console.log('/posts put', response.data)
      })
    }

    function testPut() {
     // 更新数据
      axios.put('http://localhost:3000/posts/3', {
    "title": "json-server_put", "author": "typicode" })
      .then(response => {
    
        console.log('/posts post', response.data)
      })
    }

    function testDelete() {
     // 删除数据
      a
  • 70
    点赞
  • 439
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值