小程序怎么用json-server:本地数据模拟与接口调试全攻略
在小程序开发中,后端接口未完成或前端需要独立调试时,一个稳定的本地数据模拟工具至关重要。json-server 作为一款轻量级的 RESTful API 模拟器,能基于 JSON 文件快速生成接口,非常适合小程序开发阶段的本地调试,本文将详细介绍小程序如何结合 json-server 实现本地数据模拟,从环境搭建到接口调用,再到常见问题解决,助你高效开发。
为什么小程序开发需要 json-server?
小程序开发常面临以下痛点:
- 后端接口开发滞后,前端无法联调;
- 接口字段未确定,频繁与后端沟通成本高;
- 本地测试需要模拟不同数据场景(如空数据、错误数据)。
json-server 能通过一个简单的 JSON 文件生成完整的 RESTful API(支持 GET、POST、PUT、DELETE 等请求),且支持自定义路由、数据关联等功能,无需搭建复杂后端即可满足小程序本地调试需求。
环境准备:安装 json-server
在使用 json-server 前,需确保本地已安装 Node.js(建议版本 ≥ 14.0.0),若未安装,可从 Node.js 官网 下载安装包。
全局安装 json-server
打开终端(Windows 下使用 CMD 或 PowerShell,Mac/Linux 使用 Terminal),执行以下命令:
npm install -g json-server
安装完成后,可通过 json-server --version 验证是否安装成功(输出版本号即成功)。
创建 JSON 数据源文件
json-server 的核心是数据源文件,通常是一个 db.json 文件(文件名可自定义),在项目根目录下创建 db.json,按需定义数据结构,模拟一个“商品列表”接口:
{
"products": [
{ "id": 1, "name": "iPhone 15", "price": 5999, "category": "手机" },
{ "id": 2, "name": "MacBook Pro", "price": 14999, "category": "电脑" },
{ "id": 3, "name": "AirPods Pro", "price": 1999, "category": "耳机" }
],
"categories": [
{ "id": 1, "name": "手机" },
{ "id": 2, "name": "电脑" },
{ "id": 3, "name": "耳机" }
]
}
注意:json-server 会自动为每个顶级字段(如 products、categories)生成 RESTful 接口,
- 获取所有商品:
GET /products - 获取 ID 为 1 的商品:
GET /products/1 - 新增商品:
POST /products - 更新商品:
PUT /products/1 - 删除商品:
DELETE /products/1
启动 json-server 服务
在终端中进入 db.json 所在目录,执行以下命令启动服务:
json-server --watch db.json --port 3000
参数说明:
--watch:监听db.json文件变化,修改数据后服务自动更新;--port 3000:指定服务端口(默认 3000,若被占用可改为其他端口,如--port 8080)。
启动成功后,终端会显示类似以下信息:
Resources
http://localhost:3000/products
http://localhost:3000/categories
Home
http://localhost:3000
可通过浏览器访问 http://localhost:3000/products 查看商品列表数据,验证接口是否正常。
小程序中调用 json-server 接口
小程序通过 wx.request 发起 HTTP 请求调用本地 json-server 接口,需注意:本地开发时,小程序需配置“不校验合法域名”,否则请求会被微信客户端拦截。
配置“不校验合法域名”
- 打开微信开发者工具,点击右上角“详情” → “本地设置”;
- 勾选“不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书”选项。
封装 wx.request 请求
为方便调用,可封装一个统一的请求方法,例如在 utils/api.js 中:
const API_BASE_URL = 'http://localhost:3000' // json-server 服务地址
const request = (url, method, data) => {
return new Promise((resolve, reject) => {
wx.request({
url: `${API_BASE_URL}${url}`,
method,
data,
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data)
} else {
reject(res)
}
},
fail: (err) => {
reject(err)
}
})
})
}
// 封装 GET、POST、PUT、DELETE 方法
export const get = (url) => request(url, 'GET')
export const post = (url, data) => request(url, 'POST', data)
export const put = (url, data) => request(url, 'PUT', data)
export const del = (url) => request(url, 'DELETE')
调用接口示例
在页面或组件中使用封装好的方法调用接口,在 pages/index/index.js 中获取商品列表:
import { get, post } from '../../utils/api'
Page({
data: {
products: []
},
onLoad() {
this.fetchProducts()
},
// 获取商品列表
async fetchProducts() {
try {
const products = await get('/products')
this.setData({ products })
console.log('商品列表:', products)
} catch (err) {
console.error('获取商品列表失败:', err)
wx.showToast({ title: '数据加载失败', icon: 'none' })
}
},
// 新增商品
async addProduct() {
const newProduct = { name: 'iPad Air', price: 4399, category: '平板' }
try {
await post('/products', newProduct)
wx.showToast({ title: '添加成功' })
this.fetchProducts() // 重新获取列表
} catch (err) {
console.error('添加商品失败:', err)
wx.showToast({ title: '添加失败', icon: 'none' })
}
}
})
页面展示数据
在 pages/index/index.wxml 中渲染商品列表:
<view class="container">
<view class="product-item" wx:for="{{products}}" wx:key="id">
<text>{{item.name}} - ¥{{item.price}}</text>
<text class="category">{{item.category}}</text>
</view>
<button bindtap="addProduct">添加商品</button>
</view>
进阶配置:自定义路由与数据关联
自定义路由(routes.json)
若需自定义接口路径(如将 /products 改为 /api/goods),可创建 routes.json 文件定义路由规则:
{
"/api/*": "/$1",
"/products": "/goods",
"/categories": "/types"
}
启动时添加 --routes 参数:
json-server --watch db.json --routes routes.json --port 3000
商品接口路径变为 /api/goods,分类接口变为 /api/types。
数据关联(嵌套资源)
json-server 支持数据关联,例如为商品添加分类 ID,通过 _embed 或 ?_expand 关联分类数据,修改 db.json:
{
"products": [
{ "id": 1, "name": "iPhone 15", "price": 5999, "categoryId": 1 },
{ "id": 2, "name": "MacBook Pro", "price": 14999, "categoryId": 2 }
],
"categories": [
{ "id": 1, "name": "手机" },
{ "id": 2, "name": "电脑" }
]
}
小程序中通过查询参数获取关联数据:
// 获取商品及其分类信息
const products = await get('/products?_expand=categoryId')
json-server 会自动返回包含分类详情的商品数据。
常见问题解决
请求失败:CORS 跨域问题
若小程序请求时出现“Access-Control-Allow-Origin”错误,需配置 json-server 允许跨域,安装 cors 中间件:
npm install -g cors
启动时添加 `--middlewares



还没有评论,来说两句吧...