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

相关推荐
Asize38 分钟前
Node path 与 fs 模块:从回调地狱到 async await 的异步进化
javascript·node.js
大家的林语冰3 小时前
😭 Electron 麻了,Deno 直接支持二进制应用,无需第三方桌面应用框架!
前端·javascript·node.js
Kel4 小时前
管道、IPC、Socket:你以为的三种技术,其实是同一件事
javascript·设计模式·node.js
Agent治理法学4 小时前
我开源了一套 AI Agent 框架:有性格、有规则、还会自己造工具
node.js·github
riuphan5 小时前
RAG 是什么?带你从0搭建本地向量数据库
node.js
江华森1 天前
前端构建工具 Webpack 速览
前端·webpack·node.js
无情的西瓜皮1 天前
MCP 协议实战:从零搭建一个 MCP 服务器(Node.js 版)
vue.js·人工智能·typescript·node.js
学习-学习1 天前
Node.js 现在能直接跑 TypeScript 了?Type Stripping 原理、限制与 tsx / ts-node 取舍
typescript·node.js
霍格沃兹测试开发学社测试人社区1 天前
Node.js 浏览器引擎 + Python 大脑:Playwright 混合架构爬虫系统深度解析
python·架构·node.js
小林ixn2 天前
Node.js 文件系统与路径处理:从 API 到工程化实战
node.js·编辑器·vim