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

相关推荐
瓯雅爱分享2 小时前
Java+Vue构建的采购招投标一体化管理系统,集成招标计划、投标审核、在线竞价、中标公示及合同跟踪功能,附完整源码,助力企业实现采购全流程自动化与规范化
java·mysql·vue·软件工程·源代码管理
苏打水com5 小时前
前端框架深度解析:Vue 从入门到实战,掌握渐进式开发核心
vue
无责任此方_修行中9 小时前
谁动了我的数据?一个 Bug 背后的“一行代码”真凶
后端·node.js·debug
岁月宁静11 小时前
AI 语音合成技术实践:实现文本转语音实时流式播放
前端·vue.js·node.js
Never_Satisfied14 小时前
在JavaScript / HTML / Node.js中,post方式的Content-Type属性的text的三种编码
javascript·node.js·html
棋子一名15 小时前
跑马灯组件 Vue2/Vue3/uni-app/微信小程序
微信小程序·小程序·uni-app·vue·js
苏打水com17 小时前
前端框架深度解析:Vue.js 3 从 Composition API 到生态升级,解锁企业级开发新能力
vue
学习3人组17 小时前
Node.js模块化开发实训案例
node.js·编辑器·vim
思考的笛卡尔19 小时前
Node.js性能优化:从事件循环到内存管理
性能优化·node.js