json-server在 30 秒内(认真)获得一个零编码的完整假 REST API

本文介绍了如何安装、配置和扩展JSON服务器,包括多路线处理、数据筛选、关系操作、静态文件服务,以及部署和API开发示例。

目录

入门

安装 JSON 服务器

npm install -g json-server

创建一个db.json包含一些数据的文件

{
   “帖子”:[
    { “id”:1,“title”:“ json-server ”,“author”:“ typicode ”  }
  ],
  “评论”:[
    { “id”:1,“body”:“一些评论”,“postId”:1 }
  ],
  “个人资料”:{ “名称”:“打字码”  }
}

启动 JSON 服务器

json-server --watch db.json

现在如果你去http://localhost:3000/posts/1,你会得到

{ “id”:1,“title”:“ json-server ”,“author”:“ typicode ”  }

同样在请求时,很高兴知道:

  • 如果您发出 POST、PUT、PATCH 或 DELETE 请求,更改将自动安全地保存到db.json使用lowdb
  • 您的请求正文 JSON 应该是包含对象的,就像 GET 输出一样。(例如{"name": "Foobar"}
  • Id 值是不可变的。PUT 或 PATCH 请求正文中的任何id值都将被忽略。只有在 POST 请求中设置的值才会受到尊重,但前提是尚未采用。
  • POST、PUT 或 PATCH 请求应包含Content-Type: application/json在请求正文中使用 JSON 的标头。否则它将返回 2XX 状态码,但不会对数据进行更改。

路线

根据之前的db.json文件,这里是所有的默认路由。您还可以使用添加其他路线--routes

多条路线

GET    /posts
GET    /posts/1
POST   /posts
PUT    /posts/1
PATCH  /posts/1
DELETE /posts/1

奇异路线

GET    /profile
POST   /profile
PUT    /profile
PATCH  /profile

筛选

用于.访问深层属性

GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2
GET /comments?author.name=typicode

分页

使用_page和可选地_limit对返回的数据进行分页。

在标题中,Link您将获得first、和链接。prevnextlast

GET /posts?_page=7
GET /posts?_page=7&_limit=20

默认返回10项

种类

添加_sort_order(默认升序)

GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc

对于多个字段,请使用以下格式:

GET /posts?_sort=user,views&_order=desc,asc

添加_start_end_limitX-Total-Count响应中包含标头)

GET /posts?_start=20&_end=30
GET /posts/1/comments?_start=20&_end=30
GET /posts/1/comments?_start=20&_limit=10

与Array.slice完全一样工作(即_start具有包容性和_end排他性)

运营商

添加_gte_lte获取范围

GET /posts?views_gte=10&views_lte=20

添加_ne以排除值

GET /posts?id_ne=1

添加_like到过滤器(支持正则表达式)

GET /posts?title_like=server

全文搜索

添加q

GET /posts?q=internet

关系

要包含子资源,请添加_embed

GET /posts?_embed=comments
GET /posts/1?_embed=comments

要包含父资源,请添加_expand

GET /comments?_expand=post
GET /comments/1?_expand=post

获取或创建嵌套资源(默认为一级,添加自定义路由更多)

GET  /posts/1/comments
POST /posts/1/comments

数据库

GET /db

主页

返回默认索引文件或服务./public目录

GET /

附加功能

静态文件服务器

您可以使用 JSON Server 为您的 HTML、JS 和 CSS 提供服务,只需创建一个./public目录或用于--static设置不同的静态文件目录。

mkdir public
 echo  ' hello world '  > public/index.html
json-server db.json
json-server db.json --static ./some-other-dir

替代端口

--port您可以使用以下标志在其他端口上启动 JSON Server :

$ json-server --watch db.json --port 3004

从任何地方访问

您可以使用 CORS 和 JSONP 从任何地方访问您的虚假 API。

远程模式

您可以加载远程模式。

$ json-server http://example.com/file.json
$ json-server http://jsonplaceholder.typicode.com/db

生成随机数据

使用 JS 而不是 JSON 文件,您可以通过编程方式创建数据。

// index.js
模块。export  =  ( )  =>  { 
  const  data  =  {  users : [ ]  } 
  //
  为 ( let  i  =  0 ;  i  <  1000 ;  i ++ )  { 
    data . 用户。推({  id : i ,  name : `user ${ i } `  } ) 
  }
  返回 数据
}
$ json 服务器 index.js

提示使用FakerCasualChanceJSON Schema Faker等模块。

HTTPS

在开发中设置 SSL 的方法有很多。一种简单的方法是使用hotel

添加自定义路由

创建一个routes.json文件。注意每条路线都以/.

{
   "/api/*" : " /$1 " ,
   "/:resource/:id/show" : " /:re​​source/:id " ,
   "/posts/:category" : " /posts?category=:category " ,
   "/articles \\ ?id=:id" : " /posts/:id " 
}

--routes使用选项启动 JSON 服务器。

json-server db.json --routes routes.json

现在您可以使用其他路线访问资源。

/api/posts # → /posts 
/api/posts/1   # → /posts/1 
/posts/1/show # → /posts/1 
/posts/javascript # → /posts?category=javascript 
/articles ? id=1 # → /posts/1

添加中间件

您可以使用--middlewares以下选项从 CLI 添加中间件:

// hello.js
模块。出口 =  ( req ,  res ,  next )  =>  { 
  res . 标题('X-Hello' , 'World' )
  下一个()
}
json-server db.json --middlewares ./hello.js
json-server db.json --middlewares ./first.js ./second.js

命令行使用

json-server [options] <source>

Options:
  --config, -c       Path to config file           [default: "json-server.json"]
  --port, -p         Set port                                    [default: 3000]
  --host, -H         Set host                             [default: "localhost"]
  --watch, -w        Watch file(s)                                     [boolean]
  --routes, -r       Path to routes file
  --middlewares, -m  Paths to middleware files                           [array]
  --static, -s       Set static files directory
  --read-only, --ro  Allow only GET requests                           [boolean]
  --no-cors, --nc    Disable Cross-Origin Resource Sharing             [boolean]
  --no-gzip, --ng    Disable GZIP Content-Encoding                     [boolean]
  --snapshots, -S    Set snapshots directory                      [default: "."]
  --delay, -d        Add delay to responses (ms)
  --id, -i           Set database id property (e.g. _id)         [default: "id"]
  --foreignKeySuffix, --fks  Set foreign key suffix, (e.g. _id as in post_id)
                                                                 [default: "Id"]
  --quiet, -q        Suppress log messages from output                 [boolean]
  --help, -h         Show help                                         [boolean]
  --version, -v      Show version number                               [boolean]

Examples:
  json-server db.json
  json-server file.js
  json-server http://example.com/db.json

https://github.com/typicode/json-server

您还可以在json-server.json配置文件中设置选项。

{
   “端口”:3000 
}

模块

如果您需要添加身份验证、验证或任何行为,您可以将项目作为模块与其他 Express 中间件结合使用。

简单的例子

$ npm install json-server --save-dev
// server.js 
const  jsonServer  =  require ( 'json-server' ) 
const  server  =  jsonServer . 创建( )
常量 路由器 =  jsonServer 。路由器( 'db.json' )
常量 中间件 =  jsonServer 。默认值( )

服务器。使用(中间件)
服务器。使用(路由器)
服务器。听( 3000 ,  ( )  =>  {控制台
  .log ( ' JSON 服务器正在运行' ) } )
$节点服务器.js

您提供给jsonServer.router函数的路径是相对于您启动节点进程的目录的。如果从另一个目录运行上述代码,最好使用绝对路径:

常量 路径 = 要求('路径' )
常量 路由器 =  jsonServer 。路由器(路径。加入(__dirname , 'db.json' ))

对于内存数据库,只需将对象传递给jsonServer.router().

要添加自定义选项(例如foreginKeySuffix),将对象作为第二个参数传递给jsonServer.router('db.json', { foreginKeySuffix: '_id' }).

另请注意,它jsonServer.router()可用于现有的 Express 项目。

自定义路由示例

假设您想要一个回显查询参数的路由和另一个在创建的每个资源上设置时间戳的路由。

常量 jsonServer  = 要求( 'json-server' )
常量 服务器 =  jsonServer 。创建( )
常量 路由器 =  jsonServer 。路由器( 'db.json' )
常量 中间件 =  jsonServer 。默认值( )

// 设置默认中间件(记录器、静态、cors 和无缓存)
server . 使用(中间件)


// 在 JSON Server router server之前添加自定义路由。获取( ' / echo ' ,  ( req ,  res )  =  > { 
  res.jsonp ( req.query ) } )


// 要处理 POST、PUT 和 PATCH,您需要使用 body-parser 
// 您可以使用 JSON Server
服务器使用的那个。使用(jsonServer.bodyParser )服务器。_ _ use ( ( req , res , next ) => { if ( req . method === 'POST' ) { req . body . createdAt = Date . now ( ) } // 继续 JSON Server 路由器next
    
      
      
  
  
  ( ) 
} )

// 使用默认路由器
服务器。使用(路由器)
服务器。听( 3000 ,  ( )  =>  {控制台
  .log ( ' JSON 服务器正在运行' ) } )

访问控制示例

常量 jsonServer  = 要求( 'json-server' )
常量 服务器 =  jsonServer 。创建( )
常量 路由器 =  jsonServer 。路由器( 'db.json' )
常量 中间件 =  jsonServer 。默认值( )

服务器。使用(中间件)
服务器。use ( ( req ,  res ,  next )  =>  { 
 if  ( isAuthorized ( req ) )  {  // 在此处添加您的授权逻辑
   next ( )  // 继续到 JSON Server 路由器
 }  else  { 
   res . sendStatus ( 401 ) 
 } 
} )
服务器. 使用(路由器)
服务器。听( 3000 ,  ( )  =>  {控制台
  .log ( ' JSON 服务器正在运行' ) } )

自定义输出示例

要修改响应,请覆盖router.render方法:

// 在这个例子中,返回的资源将被包装在一个 body 属性
router中。渲染 =  ( req ,  res )  =>  { 
  res . jsonp ( { 
    body : res . locals . data 
  } ) 
}

您可以为响应设置自己的状态代码:

// 在这个例子中,我们模拟了一个服务器端错误响应
路由器。渲染 =  ( req ,  res )  =>  { 
  res . 状态(500 )。jsonp ( { 
    error : "这里的错误信息" 
  } ) 
}

重写器示例

要添加重写规则,请使用jsonServer.rewriter()

// 在 server.use(router) 
server之前添加这个。使用( jsonServer . rewriter ( { 
  '/api/*' : '/$1' , 
  '/blog/:resource/:id/show' : '/:resource/:id' 
} ) )

在另一个端点上挂载 JSON 服务器示例

或者,您也可以将路由器安装在/api.

服务器。使用('/api' , 路由器)

API

jsonServer.create()

返回一个 Express 服务器。

jsonServer.defaults([options])

返回 JSON 服务器使用的中间件。

  • 选项
    • static静态文件的路径
    • logger启用记录器中间件(默认值:true)
    • bodyParser启用 body-parser 中间件(默认值:true)
    • noCors禁用 CORS(默认值:false)
    • readOnly只接受 GET 请求(默认值:false)

jsonServer.router([path|object], [options])

返回 JSON 服务器路由器。

部署

您可以部署 JSON 服务器。例如,JSONPlaceholder是一个由 JSON Server 提供支持并在 Heroku 上运行的在线虚假 API。

链接

视频

文章

第三方工具

执照

麻省理工学院

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值