如果有更高级的定制使用,请往下看:
安装:
$ npm install json-server --save-dev
基本使用:
// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
启动:
$ node server.js
多文件(多路由)
server.use(router1)
server.use("/api",router2)
middlewares的配置:
static path to static files
logger enable logger middleware (default: true)
bodyParser enable body-parser middleware (default: true)
noCors disable CORS (default: false)
readOnly accept only GET requests (default: false)
示例:
const middlewares = jsonServer.defaults({
readOnly:false,
logger:true,
bodyParser:true,
noCors:false,
})
server.use(middlewares)
访问控制
server.use((req, res, next) => {
if (isAuthorized(req)) { // add your authorization logic here
next() // continue to JSON Server router
} else {
res.sendStatus(401)
}
})
应用: 利用多个网络资源数据启动json-server
const jsonServer = require('json-server')
const request=require('request')
const url1="https://api.myjson.com/bins/rze4n"
const url2="https://api.myjson.com/bins/1bc7rz"
let obj={}
const server = jsonServer.create()
request({url:url1,json:true},(err,resp,data)=>{
obj.books=data.books
request({url:url2,json:true},(err,resp,data)=>{
obj.users=data.users
startServer(3000,obj)
})
})
function startServer(port,db) {
const router = jsonServer.router(db)
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use("/manager",router)
server.listen(port, () => {
console.log('JSON Server is running')
})
}
更加完整的实际例子:
const jsonServer = require('json-server')
const request=require('request')
const base="http://10.100.21.52:8080/Note.do?"
const url1=base+"status=initTop_menu&netAwId=35&wId=18&sort=top"
const url2=base+"1&status=getFoot&wId=18&wsSort=foot&netAwId=35"
const url3=base+"status=slide&wId=18&netAwId=35"
const url4=base+"status=indexlanmu&wId=18&netAwId=35&top=5"
const url5=base+"111&status=linkall&netAwId=35&wId=18"
let obj={}
const server = jsonServer.create()
//多个异步函数串联,完成数据加载
request({url:url1,json:true},(err,resp,data)=>{
obj.menus=data
request({url:url2,json:true},(err,resp,data)=>{
obj.wsNote=data
request({url:url3,json:true},(err,resp,data)=>{
obj.wsPicUrl=data
request({url:url4,json:true},(err,resp,data)=>{
obj.papers=data;
request({url:url5,json:true},(err,resp,data)=>{
obj.empty=data
startServer(3000,obj)
})
})
})
})
})
//启动 json-server
function startServer(port,db) {
const router = jsonServer.router(db)
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use("/api",router)
server.listen(port, () => {
console.log('JSON Server is running')
for (let p in obj){
console.log("http://localhost:"+port+"/api/"+p)
}
})
}