Json-server 模拟后端接口

json-server,模拟rest接口,自动生成增删改查接口。(官网地址:json-server - npm)

使用方法:

1. 安装json-server,npm i json-server -g

2. 创建json文件,文件中存储list数据,db.json

objectivec 复制代码
{
  "posts": [
    { "id": "1", "title": "a title", "views": 100 },
    { "id": "2", "title": "another title", "views": 200 }
  ],
  "comments": [
    { "id": "1", "text": "a comment about post 1", "postId": "1" },
    { "id": "2", "text": "another comment about post 1", "postId": "1" }
  ],
  "profile": {
    "name": "typicode"
  }
}

3. 启动 json-server

终端进入到db.json所在目录,执行 npx json-server db.json 命令启动服务

注意:如果遇到下面报错,需要升级node版本

bash 复制代码
PS D:\workspace\learnui\vuex-demo\db> npx json-server index.json
npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
file:///C:/Users/nantian/AppData/Roaming/npm/node_modules/json-server/lib/bin.js:4
import { parseArgs } from 'node:util';
         ^^^^^^^^^
SyntaxError: The requested module 'node:util' does not provide an export named 'parseArgs'
    at ModuleJob._instantiate (node:internal/modules/esm/module_job:128:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:194:5)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:61:12)

服务启动成功,默认端口号3000

4. 访问接口

bash 复制代码
GET    http://localhost:3000/posts
GET    http://localhost:3000/posts/:id
POST   http://localhost:3000/posts
PUT    http://localhost:3000/posts/:id
PATCH  http://localhost:3000/posts/:id
DELETE http://localhost:3000/posts/:id


GET   http://localhost:3000/profile
PUT   http://localhost:3000/profile
PATCH http://localhost:3000/profile

5. json-server其他参数说明

PS D:\workspace\learnui\vuex-demo> json-server --help

Usage: json-server [options] <file>

Options:

-p, --port <port> Port (default: 3000)

-h, --host <host> Host (default: localhost)

-s, --static <dir> Static files directory (multiple allowed)

--help Show this message

--version Show version number

相关推荐
Sammyyyyy7 分钟前
2025年,Javascript后端应该用 Bun、Node.js 还是 Deno?
开发语言·javascript·node.js
Q_Q5110082852 小时前
python的软件工程与项目管理课程组学习系统
spring boot·python·django·flask·node.js·php·软件工程
outsider_友人A4 小时前
前端也想写后端(3)中间件Middleware、管道Pipes、拦截器Interceptors
前端·node.js·nestjs
i紸定i6 小时前
解决html-to-image在 ios 上dom里面的图片不显示出来
前端·ios·vue·html·html-to-image
爱加班的猫1 天前
Node.js 中 require 函数的原理深度解析
前端·node.js
冲!!1 天前
使用nvm查看/安装node版本
前端·node.js·node·nvm
萌萌哒草头将军2 天前
Node.js v24.6.0 新功能速览 🚀🚀🚀
前端·javascript·node.js
行星0082 天前
mac 通过homebrew 安装和使用nvm
macos·npm·node.js
尚学教辅学习资料2 天前
Vue3从入门到精通: 4.5 数据持久化与同步策略深度解析
vue·数据持久化
kngines2 天前
【Node.js从 0 到 1:入门实战与项目驱动】1.3 Node.js 的应用场景(附案例与代码实现)
node.js