首页 > 其他分享 >json-server详细模拟GET、POST、DELETE等接口数据教程

json-server详细模拟GET、POST、DELETE等接口数据教程

时间:2024-10-20 09:50:53浏览次数:3  
标签:GET server json 3000 post id 模拟

引言

在前端开发过程中,我们经常需要在后端API尚未就绪的情况下模拟接口数据。json-server是一个强大而灵活的工具,可以帮助我们快速创建一个模拟的RESTful API。本文将详细介绍如何使用json-server来模拟GET、POST、PUT、PATCH、DELETE等常用的HTTP方法,以及如何处理复杂的数据关系、自定义路由和中间件。无论你是前端开发新手还是经验丰富的工程师,本教程都将帮助你更高效地进行前后端分离开发。

目录

  1. json-server简介
  2. 安装json-server
  3. 创建详细的数据文件
  4. 启动json-server
  5. 模拟GET请求
  6. 模拟POST请求
  7. 模拟PUT请求
  8. 模拟PATCH请求
  9. 模拟DELETE请求
  10. 高级功能
    • 自定义路由
    • 自定义中间件
  11. 在前端项目中使用json-server
  12. 最佳实践和注意事项
  13. 总结

1. json-server简介

json-server是一个Node模块,可以在30秒内创建一个完整的fake REST API。它不需要编写任何代码,只需要一个JSON文件作为数据源。json-server提供了以下主要功能:

  • 基于JSON文件快速创建REST API
  • 支持GET、POST、PUT、PATCH、DELETE等HTTP方法
  • 支持过滤、分页、排序和全文搜索
  • 可以添加自定义路由
  • 可以使用自定义中间件
  • 支持静态文件服务
  • 支持CORS和JSONP

2. 安装json-server

首先,我们需要安装json-server。确保你的系统已经安装了Node.js,然后在命令行中运行以下命令:

npm install -g json-server

这将全局安装json-server,使你可以在任何目录下使用它。

3. 创建详细的数据文件

json-server使用一个JSON文件作为数据源。让我们创建一个名为db.json的文件,它将模拟一个简单的博客系统的数据。这个数据文件将包含用户、文章、评论、分类和标签等实体,以及它们之间的关系。

{
  "users": [
    {
      "id": 1,
      "username": "alice_wonder",
      "email": "[email protected]",
      "name": "Alice Wonderland",
      "role": "admin",
      "created_at": "2024-01-01T00:00:00Z"
    },
    {
      "id": 2,
      "username": "bob_builder",
      "email": "[email protected]",
      "name": "Bob The Builder",
      "role": "author",
      "created_at": "2024-01-02T00:00:00Z"
    },
    {
      "id": 3,
      "username": "charlie_chocolate",
      "email": "[email protected]",
      "name": "Charlie Bucket",
      "role": "reader",
      "created_at": "2024-01-03T00:00:00Z"
    }
  ],
  "posts": [
    {
      "id": 1,
      "title": "Introduction to json-server",
      "content": "json-server is a great tool for mocking REST APIs...",
      "author_id": 1,
      "status": "published",
      "created_at": "2024-02-01T10:00:00Z",
      "updated_at": "2024-02-01T10:00:00Z"
    },
    {
      "id": 2,
      "title": "Advanced json-server techniques",
      "content": "In this post, we'll explore some advanced json-server features...",
      "author_id": 2,
      "status": "draft",
      "created_at": "2024-02-05T14:30:00Z",
      "updated_at": "2024-02-06T09:15:00Z"
    },
    {
      "id": 3,
      "title": "RESTful API Design Best Practices",
      "content": "When designing a RESTful API, it's important to consider...",
      "author_id": 1,
      "status": "published",
      "created_at": "2024-02-10T11:45:00Z",
      "updated_at": "2024-02-10T11:45:00Z"
    }
  ],
  "comments": [
    {
      "id": 1,
      "post_id": 1,
      "user_id": 3,
      "content": "Great introduction! This helped me a lot.",
      "created_at": "2024-02-02T08:30:00Z"
    },
    {
      "id": 2,
      "post_id": 1,
      "user_id": 2,
      "content": "I've been using json-server for a while, and it's fantastic!",
      "created_at": "2024-02-03T16:45:00Z"
    },
    {
      "id": 3,
      "post_id": 3,
      "user_id": 3,
      "content": "These best practices are really useful. Thanks for sharing!",
      "created_at": "2024-02-11T10:00:00Z"
    }
  ],
  "categories": [
    {
      "id": 1,
      "name": "Web Development",
      "slug": "web-dev"
    },
    {
      "id": 2,
      "name": "API Design",
      "slug": "api-design"
    },
    {
      "id": 3,
      "name": "Tools & Libraries",
      "slug": "tools-libs"
    }
  ],
  "tags": [
    {
      "id": 1,
      "name": "json-server",
      "slug": "json-server"
    },
    {
      "id": 2,
      "name": "REST API",
      "slug": "rest-api"
    },
    {
      "id": 3,
      "name": "mock data",
      "slug": "mock-data"
    },
    {
      "id": 4,
      "name": "frontend development",
      "slug": "frontend-dev"
    }
  ],
  "post_categories": [
    {
      "id": 1,
      "post_id": 1,
      "category_id": 3
    },
    {
      "id": 2,
      "post_id": 2,
      "category_id": 3
    },
    {
      "id": 3,
      "post_id": 3,
      "category_id": 2
    }
  ],
  "post_tags": [
    {
      "id": 1,
      "post_id": 1,
      "tag_id": 1
    },
    {
      "id": 2,
      "post_id": 1,
      "tag_id": 3
    },
    {
      "id": 3,
      "post_id": 2,
      "tag_id": 1
    },
    {
      "id": 4,
      "post_id": 2,
      "tag_id": 2
    },
    {
      "id": 5,
      "post_id": 3,
      "tag_id": 2
    },
    {
      "id": 6,
      "post_id": 3,
      "tag_id": 4
    }
  ]
}

这个数据文件包含了用户、文章、评论、分类、标签以及它们之间的关系,允许我们模拟复杂的查询和数据操作。

4. 启动json-server

在命令行中,进入db.json所在的目录,然后运行:

json-server --watch db.json

现在,json-server已经在http://localhost:3000上运行。你可以通过浏览器或API测试工具访问这个地址来查看和操作数据。

5. 模拟GET请求

json-server支持各种复杂的GET请求。以下是一些常用的例子:

5.1 获取所有用户

GET http://localhost:3000/users

5.2 获取单个用户

GET http://localhost:3000/users/1

5.3 筛选用户

GET http://localhost:3000/users?role=author

5.4 分页

GET http://localhost:3000/posts?_page=1&_limit=10

5.5 获取特定作者的所有文章

GET http://localhost:3000/posts?author_id=1

5.6 获取特定文章的所有评论

GET http://localhost:3000/comments?post_id=1

5.7 全文搜索

GET http://localhost:3000/posts?q=json-server

5.8 复杂过滤和排序

GET http://localhost:3000/posts?status=published&_sort=created_at&_order=desc

6. 模拟POST请求

要添加新数据,我们可以发送POST请求。例如,添加新用户:

POST http://localhost:3000/users
Content-Type: application/json

//发送的数据
{
  "username": "david_copperfield",
  "email": "[email protected]",
  "name": "David Copperfield",
  "role": "author",
  "created_at": "2024-03-01T00:00:00Z"
}

json-server会自动为新记录分配一个唯一的id

7. 模拟PUT请求

PUT请求用于更新整个资源。例如,更新用户信息:

PUT http://localhost:3000/users/4
Content-Type: application/json

{
  "username": "david_copperfield",
  "email": "[email protected]",
  "name": "David Copperfield",
  "role": "admin",
  "created_at": "2024-03-01T00:00:00Z"
}

8. 模拟PATCH请求

PATCH请求用于部分更新资源。例如,只更新用户的邮箱:

PATCH http://localhost:3000/users/4
Content-Type: application/json

{
  "email": "[email protected]"
}

9. 模拟DELETE请求

要删除一个资源,发送DELETE请求到特定的ID:

DELETE http://localhost:3000/users/4

10. 高级功能

10.1 自定义路由

创建一个routes.json文件:

{
  "/api/*": "/$1",
  "/blog/:resource/:id/show": "/:resource/:id",
  "/articles/published": "/posts?status=published",
  "/posts/:id/comments": "/comments?post_id=:id"
}

启动服务器时使用--routes选项:

json-server db.json --routes routes.json

10.2 自定义中间件

创建一个middleware.js文件:

module.exports = (req, res, next) => {
  if (req.method === 'POST') {
    req.body.created_at = new Date().toISOString()
  }
  if (req.method === 'PUT' || req.method === 'PATCH') {
    req.body.updated_at = new Date().toISOString()
  }
  next()
}

启动服务器时使用--middlewares选项:

json-server db.json --middlewares middleware.js

11. 在前端项目中使用json-server

以Vue.js和axios为例,演示如何在前端项目中使用json-server:

import axios from 'axios';

const API_BASE_URL = 'http://localhost:3000';

// GET请求 - 获取所有已发布的文章
async function getPublishedPosts() {
  try {
    const response = await axios.get(`${API_BASE_URL}/posts?status=published`);
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching published posts:', error);
  }
}

// POST请求 - 创建新文章
async function createPost(postData) {
  try {
    const response = await axios.post(`${API_BASE_URL}/posts`, postData);
    console.log('New post created:', response.data);
  } catch (error) {
    console.error('Error creating post:', error);
  }
}

// PUT请求 - 更新文章
async function updatePost(postId, updatedData) {
  try {
    const response = await axios.put(`${API_BASE_URL}/posts/${postId}`, updatedData);
    console.log('Post updated:', response.data);
  } catch (error) {
    console.error('Error updating post:', error);
  }
}

// DELETE请求 - 删除文章
async function deletePost(postId) {
  try {
    await axios.delete(`${API_BASE_URL}/posts/${postId}`);
    console.log('Post deleted successfully');
  } catch (error) {
    console.error('Error deleting post:', error);
  }
}

12. 最佳实践和注意事项

  1. 数据一致性: 确保你的db.json文件中的数据保持一致性,特别是在处理关系数据时。
  2. 备份数据: json-server会直接修改db.json文件。在开发过程中,定期备份你的数据文件是个好习惯。
  3. 性能考虑: 虽然json-server对于开发和测试很有用,但它并不适合处理大量数据或高并发请求。在这种情况下,考虑使用更强大的数据库解决方案。
  4. 安全性: json-server没有内置的认证和授权机制。在处理敏感数据时,确保在生产环境中实现适当的安全措施。
  5. 版本控制: 将你的db.jsonroutes.json和自定义中间件文件纳入版本控制系统,以便团队协作和追踪变更。
  6. 模拟延迟: 在实际项目中,API响应通常不会立即返回。使用--delay选项模拟网络延迟,以更好地模拟真实环境:
    json-server --watch db.json --delay 1000
  7. 使用Lowdb: json-server内部使用Lowdb。如果你需要更高级的数据操作,可以直接使用Lowdb来自定义json-server的行为。
  8. 结合Faker.js: 如果你需要生成大量逼真的测试数据,可以考虑结合使用Faker.js来自动生成数据。

 

13. 高级应用场景

13.1 模拟文件上传

虽然json-server主要用于模拟JSON API,但我们也可以模拟文件上传功能:

  1. 创建一个public文件夹来存储"上传"的文件。
  2. 在启动json-server时指定静态文件目录:
    json-server --watch db.json --static ./public
  3. 在前端,你可以使用FormData来模拟文件上传:
    async function uploadFile(file) {
      const formData = new FormData();
      formData.append('file', file);
      
      try {
        const response = await axios.post('http://localhost:3000/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        console.log('File uploaded:', response.data);
      } catch (error) {
        console.error('Error uploading file:', error);
      }
    }

13.2 模拟实时数据更新

虽然json-server不直接支持WebSocket,但我们可以结合使用json-serversocket.io来模拟实时数据更新:

  1. 安装必要的包:
    npm install json-server socket.io
  2. 创建一个server.js文件:
    const jsonServer = require('json-server');
    const server = jsonServer.create();
    const router = jsonServer.router('db.json');
    const middlewares = jsonServer.defaults();
    const port = 3000;
    
    server.use(middlewares);
    server.use(router);
    
    const httpServer = server.listen(port, () => {
      console.log(`JSON Server is running on port ${port}`);
    });
    
    const io = require('socket.io')(httpServer);
    
    io.on('connection', (socket) => {
      console.log('A user connected');
    
      socket.on('dataUpdate', (data) => {
        // 更新db.json
        const db = router.db;
        db.get('posts').push(data).write();
        
        // 广播更新到所有客户端
        io.emit('newData', data);
      });
    
      socket.on('disconnect', () => {
        console.log('User disconnected');
      });
    });
  3. 在前端使用Socket.IO客户端来接收实时更新:
    import io from 'socket.io-client';
    
    const socket = io('http://localhost:3000');
    
    socket.on('newData', (data) => {
      console.log('Received new data:', data);
      // 更新前端状态
    });
    
    // 发送数据更新
    function sendUpdate(data) {
      socket.emit('dataUpdate', data);
    }

14. 故障排除

在使用json-server时,你可能会遇到一些常见问题。以下是一些解决方案:

  1. 跨域问题: 如果遇到跨域错误,确保在启动json-server时添加--cors选项:
    json-server --watch db.json --cors
  2. 端口冲突: 如果默认的3000端口被占用,可以使用--port选项指定其他端口:
    json-server --watch db.json --port 3001
  3. 数据不更新: 确保你的PUT/PATCH请求包含了完整的对象结构。json-server不会自动合并部分更新。
  4. 查询参数不工作: 检查你的URL编码。某些特殊字符可能需要编码,例如&应该编码为%26
  5. 自定义路由不生效: 确保你的routes.json文件格式正确,并且在启动时正确指定了该文件。

 

15. 总结

json-server是一个强大而灵活的工具,可以极大地提高前端开发的效率。通过本教程,我们详细介绍了如何使用json-server来模拟各种HTTP方法,包括GET、POST、PUT、PATCH和DELETE。我们还探讨了一些高级功能,如自定义路由、中间件,以及如何处理更复杂的应用场景。

json-server的优势在于:

  • 快速搭建模拟API,无需编写后端代码
  • 支持复杂的数据关系和查询
  • 可以轻松集成到现有的前端开发工作流中
  • 提供了丰富的定制选项,满足各种模拟需求

然而,也要注意json-server的局限性:

  • 不适合用于生产环境
  • 对于大型数据集可能会有性能问题
  • 缺乏内置的安全特性

总的来说,json-server是前端开发、原型设计和测试过程中的得力助手。通过合理使用json-server,你可以显著提高开发效率,更快地迭代和验证你的前端应用。

希望这个详细的教程能够帮助你更好地使用json-server,如果你有任何问题或需要进一步的说明,欢迎在评论区留言。祝你编码愉快!

标签:GET,server,json,3000,post,id,模拟
From: https://blog.csdn.net/Play_Sai/article/details/143020117

相关文章

  • socketserver实现文件上传
    1.服务端importosimportjsonimportsocketserverclassMyTCPHandler(socketserver.BaseRequestHandler):defput(self,*args):cmd_dic=args[0]filename=cmd_dic["filename"]filesize=cmd_dic["size"]ifos.p......
  • Error response from daemon: Get “https://registry-1.docker.io/v2/“: net/http:
    目录1问题2解决办法3后记1问题Errorresponsefromdaemon:Get“https://registry-1.docker.io/v2/”:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)2解决办法touch/etc/docker/daemon.......
  • Get “https://registry-1.docker.io/v2/“: proxyconnect tcp: dial tcp: lookup pro
    docker通过代理配置上网无法pullanbox使用代理配置文件解决1.创建代理配置文件运行以下命令创建配置文件:sudomkdir-p/etc/systemd/system/docker.service.dsudotouch/etc/systemd/system/docker.service.d/http-proxy.conf2.编辑配置文件使用nano文本编辑器打......
  • “JsonConvert”同时存在于“Newtonsoft.Json.Net20, Version=3.5.0.0, Culture=neutr
    原因是两个dll冲突了。需要去掉一个。Newtonsoft.Json(也称为Json.NET)是一个流行的开源JSON框架,用于.NET,它以其高性能、易用性和广泛的功能而闻名。它支持丰富的数据操作和序列化属性设置,如自定义转换器、日期时间格式控制、命名策略等。Json.NET还提供了序列化特性,如JsonObjectA......
  • 最新 client-java 调用 k8s ApiServer
    创建权限绑定sa-role.yamlapiVersion:v1kind:ServiceAccountmetadata:name:my-admin#账号名namespace:kube-system---apiVersion:rbac.authorization.k8s.io/v1kind:ClusterRolemetadata:annotations:rbac.authorization.kubernetes.io/autoupdat......
  • java 调用 k8s 的 apiserver
    创建serviceaccountserviceaccount.yamlapiVersion:v1kind:ServiceAccountmetadata:name:myadminnamespace:default创建集群角色ClusterRoleclusterrole.yamlapiVersion:rbac.authorization.k8s.io/v1kind:ClusterRolemetadata:name:my-clusterrolerul......
  • uni-app小程序(快手、抖音)getCurrentPages使用坑位记录2
    前情uni-app是我比较喜欢的跨平台框架,它能开发小程序/H5/APP(安卓/iOS),重要的是对前端开发友好,自带的IDE让开发体验也挺棒的,现公司项目就是主推uni-app,我主要负责抖音和快手端小程序。坑位公司历史原因项目有APP端小程序端,但并不使用uni-app的一端发布所有平台,各端都有它的开发......
  • SpringBoot 项目的方法名是否添加@Transactional注解,以及SQL语句(SQLServer数据库)是
    项目改用SpringDataJDBC并手动配置DataSource之后,@Transactional注解一直不起作用。这两天研究了一下,注解不起作用,主要是没有配置TransactionManager的事,配置完TransactionManager之后,@Transactional注解就起作用了。但是配置完又发现,用jdbcTemplate.queryForList()方法执......
  • Get Things Done with Prompt Engineering and LangChain: 构建强大的AI应用
    探索AI应用开发的新境界在人工智能快速发展的今天,如何高效地利用大型语言模型(LLMs)构建实用的AI应用,已经成为许多开发者关注的焦点。GitHub上一个名为'GetThingsDonewithPromptEngineeringandLangChain'的开源项目,为我们提供了一个绝佳的学习资源。这个项目不仅包含了......
  • com.microsoft.sqlserver.jdbc.SQLServerException: Software caused connection abor
    报错原因今天新安装的SQLSERVER2012,于是ruoyi框架就测试多数据源,结果发现无法连接。奇怪的是navicat可以连接,SQLServerManagementStudio也可以正常连接。我们都知道SQLSERVER默认的端口是1433,结果我用1433连接不上。于是查询了端口,发现只有1434端口开着,这个端口一看就是......