环境
需要安装 node
https://nodejs.org/en/
开始
1.新建项目 mkdir rest-api-demo && cd rest-api-demo
2.初始化项目 npm init
3.安装 npm install --save-dev json-server
4.在项目根目录下,新建一个 JSON 文件db.json
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
5.打开 package.json
,在 scripts
字段添加一行
"scripts": {
"server": "json-server db.json", // 新加行
"test": "..."
}
6.启动服务 npm run server
\{^_^}/ hi!
Loading db.json
Done
Resources
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile
三个接口已经生成,支持post(新增) delete(删除) put(修改) get(查询)
;
推荐使用 postman
进行测试
自定义路由
1.创建一个JSON文件 routes.json
必须以/
开始
{
"/api/": "/",
"/blog/:resource/:id/show": "/:resource/:id",
"/blog/:category": "/posts/:id?category=:category"
}
2.修改启动参数 package.json
"scripts": {
"server": "json-server db.json --routes routes.json", // 修改行
"test": "..."
}
3.启动服务 npm run server
\{^_^}/ hi!
Loading db.json
Loading routes.json
Done
Resources
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile
Other routes
/api/ -> /
/blog/:resource/:id/show -> /:resource/:id
/blog/:category -> /posts/:id?category=:category