前端基础-json-server与axios

第7章 json-server与axios

一个项目从立项开始,一般都是前后端同时进行编码工作的,而此时前端需要的接口和数据后台都是无法提供的;

7.1 json-server 使用

使用全局安装 :npm install json-server -g

json-server 会将一个json文件作为数据库来存储数据,对json数据的格式是有要求的,如data.json的内容:

{
  "tb1": [
    {
      "id": 1,
      "title": "标题1",
      "author": "描述信息1"
    },
    {
      "id": 2,
      "title": "标题2",
      "author": "描述信息2"
    }
  ],
  "tb2": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "tb3": {
    "name": "typicode"
  }
}

启动服务: json-server --watch data.json

启动成功后,提示信息如下:

$ json-server --watch data.json

  \{^_^}/ hi!

  Loading data.json
  Done

  Resources
  http://localhost:3000/tb1
  http://localhost:3000/tb2
  http://localhost:3000/tb3

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

得到tb1所有的数据 GET: http://localhost:3000/tb1

根据id得到数据 GET : http://localhost:3000/tb1/2

添加一条数据 POST: http://localhost:3000/tb1

删除一条数据 DELETE: http://localhost:3000/tb1/2

模糊查找 GET : http://localhost:3000/tb1?title_like=标题

根据id修改数据 PUT: http://localhost:3000/tb1/1

注意:json-server 严格遵循 HTTP 请求语义进行数据处理

在这里插入图片描述

7.2 axios

我们在构建应用时需要访问一个 API 并展示其数据。做这件事的方法有好几种,而使用基于 Promise 的 HTTP 客户端 axios 则是其中非常流行的一种。

<script src="./axios.js"></script>
<script>
    // 获取全部数据
    axios.get('http://localhost:3000/list_data')
    .then((data)=>{
        console.log(data);
    });

    // 获取一条数据
    axios.get('http://localhost:3000/list_data/2')
    .then((data)=>{
        console.log(data);
    })
    
    // 添加一条数据
    axios.post('http://localhost:3000/list_data',{stat:false,title:'喝水'})
    .then((d)=>{
        console.log(d);
    }).catch(error => console.log(error))

     // 删除一条数据
     axios.delete('http://localhost:3000/list_data/4')
    .then((d)=>{
        console.log(d);
    }).catch(error => console.log(error))

     // 修改一条数据
     axios.put('http://localhost:3000/list_data/6',{title:'hhhhhh'})
    .then((d)=>{
        console.log(d);
    }).catch(error => console.log(error))
</script>
发布了1825 篇原创文章 · 获赞 1948 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/105118743