使用json-server模拟后台数据

本文介绍如何通过安装Node.js及全局安装json-server来快速搭建一个本地JSON数据服务器。包含详细的安装步骤、命令行参数说明及示例,帮助开发者轻松创建用于前端应用测试的数据接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先在电脑中需要安装nodejs,然后全局安装json server.

npm install json-server -g

使用linux和macos的电脑需要加上sudo

sudo npm install json-server -g

安装完成后可以用json-server -h命令检查是否安装成功,成功后会出现

json-server [options] <source>

选项:
  --config, -c               Path to config file    [默认值: "json-server.json"]
  --port, -p                 Set port                             [默认值: 3000]
  --host, -H                 Set host                        [默认值: "0.0.0.0"]
  --watch, -w                Watch file(s)                                [布尔]
  --routes, -r               Path to routes file
  --middlewares, -m          Paths to middleware files                    [数组]
  --static, -s               Set static files directory
  --read-only, --ro          Allow only GET requests                      [布尔]
  --no-cors, --nc            Disable Cross-Origin Resource Sharing        [布尔]
  --no-gzip, --ng            Disable GZIP Content-Encoding                [布尔]
  --snapshots, -S            Set snapshots directory               [默认值: "."]
  --delay, -d                Add delay to responses (ms)
  --id, -i                   Set database id property (e.g. _id)  [默认值: "id"]
  --foreignKeySuffix, --fks  Set foreign key suffix (e.g. _id as in post_id)
                                                                  [默认值: "Id"]
  --quiet, -q                Suppress log messages from output            [布尔]
  --help, -h                 显示帮助信息                                 [布尔]
  --version, -v              显示版本号                                   [布尔]

示例:
  json-server db.json
  json-server file.js
  json-server http://example.com/db.json

https://github.com/typicode/json-server
安装完成后,在自己的项目目录下建立一个xxx.json文件,例如mock-data.json,并写入数据

{
    "users": [
        {
            "id" : 1,
            "username": "aaa",
            "password": "aaa"
        },
        {
            "id" : 2,
            "username": "bbb",
            "password": "bbb"
        },
        {
            "id": 3,
            "username": "ccc",
            "password": "ccc"
        }
    ]   
}

然后使用命令行工具进入该json文件所在目录,执行json-server --watch xxx.json 【json-server --watch xxx.json --port 3000(端口可随意指定)

执行成功返回:

\{^_^}/ hi!

  Loading mock-data.json
  Done

  Resources
  http://localhost:3000/users

  Home
  http://localhost:3000



页面信息:



                
### Json-server 详细使用指南 #### 一、Json-server 简介 `json-server` 是一种轻量级的工具,用于快速构建 RESTful API 接口。其核心特点是基于 JSON 数据文件自动生成接口,并支持 CRUD 操作[^3]。 --- #### 二、安装与验证 为了能够在任何目录下运行 `json-server` 命令,需通过 `-g` 参数将其安装到全局环境中。以下是具体命令: ```bash npm install -g json-server ``` 完成安装后,可通过以下命令确认版本号以验证安装是否成功: ```bash json-server --version ``` 如果返回类似如下信息,则表示安装成功: ``` 0.14.0 ``` 此过程确保了环境配置无误[^1]。 --- #### 三、创建数据库文件 (db.json) `json-server` 使用名为 `db.json` 的文件作为数据存储的核心部分。该文件是一个标准的 JSON 对象结构,其中键代表资源名称,而值则为数组形式的数据集合。例如: ```json { "posts": [ { "id": 1, "title": "foo", "author": "bar" }, { "id": 2, "title": "baz", "author": "qux" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ] } ``` 上述示例定义了一个包含两篇文章 (`posts`) 和一条评论 (`comments`) 的简单数据库模型[^2]。 --- #### 四、启动服务 在项目根目录(即放置有 `db.json` 文件的位置),执行以下命令即可启动服务: ```bash json-server db.json ``` 默认情况下,服务会监听于 `http://localhost:3000` 地址,并自动根据 `db.json` 中的内容生成对应的 RESTful 路由规则。例如,访问 `/posts` 将返回所有文章列表;访问 `/posts/:id` 则可获取指定 ID 的单条记录[^3]。 --- #### 五、高级功能扩展 除了基本的功能外,`json-server` 还提供了多种增强选项供开发者灵活定制需求: 1. **修改端口号** 如果希望更改默认端口(3000),可以借助 `--port` 参数实现: ```bash json-server db.json --port 8080 ``` 2. **启用延迟模式** 开发过程中可能需要模拟网络请求耗时情况,此时可用 `--delay` 设置响应延时时间(单位毫秒): ```bash json-server db.json --delay 1000 ``` 3. **静态页面托管** 支持额外加载 HTML 或其他静态资产文件夹路径设置: ```bash json-server db.json --static ./public ``` 4. **路由重写** 自定义 URL 映射关系满足特定业务场景下的特殊命名约定: ```javascript const router = require('express').Router(); router.get('/custom-endpoint', function(req, res) { res.json({ customKey: 'customValue' }); }); module.exports = router; ``` 并通过参数引入外部脚本逻辑控制流程走向[^2]。 --- #### 六、总结 综上所述,`json-server` 提供了一种便捷高效的解决方案帮助前端工程师独立开展工作而不必等待完整的后台架构就绪之前先行测试交互效果。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值