json-server 中的自定义路由使用 Node.js
Custom routes in json-server using Node.js
我在使用自定义路由请求部署在 json-server 中的 db.json 时发现问题。
例如,对于下面给定的 json,我想按姓名访问选民,因此当我键入此内容时
url:
https://localhost:3000/data/1/sessions/:sessionId/voters/:voterName
其中sessionId
和voterName
是parameterized
,响应应该是{"voterName"}
db.json:
{
"id": 1,
"name": "Angular Connect",
"date": "2036-09-25T23:00:00.000Z",
"time": "10:00 am",
"price": 599.99,
"imageUrl": "/assets/images/angularconnect-shield.png",
"location": {
"address": "1057 DT",
"city": "London",
"country": "England"
},
"sessions": [
{
"id": 1,
"name": "Using Angular 4 Pipes",
"presenter": "Peter Bacon Darwin",
"duration": 1,
"level": "Intermediate",
"abstract": "Learn all about the new pipes in Angular 4, both \n how to write them, and how to get the new AI CLI to write \n them for you. Given by the famous PBD, president of Angular \n University (formerly Oxford University)",
"voters": [
"bradgreen",
"igorminar",
"martinfowler"
]
},
{
"id": 2,
"name": "Getting the most out of your dev team",
"presenter": "Jeff Cross",
"duration": 1,
"level": "Intermediate",
"abstract": "We all know that our dev teams work hard, but with \n the right management they can be even more productive, without \n overworking them. In this session I'll show you how to get the \n best results from the talent you already have on staff.",
"voters": [
"johnpapa",
"bradgreen",
"igorminar",
"martinfowler"
]
},
{
"id": 3,
"name": "Angular 4 Performance Metrics",
"presenter": "Rob Wormald",
"duration": 2,
"level": "Advanced",
"abstract": "Angular 4 Performance is hot. In this session, we'll see \n how Angular gets such great performance by preloading data on \n your users devices before they even hit your site using the \n new predictive algorithms and thought reading software \n built into Angular 4.",
"voters": []
},
{
"id": 4,
"name": "Angular 5 Look Ahead",
"presenter": "Brad Green",
"duration": 2,
"level": "Advanced",
"abstract": "Even though Angular 5 is still 6 years away, we all want \n to know all about it so that we can spend endless hours in meetings \n debating if we should use Angular 4 or not. This talk will look at \n Angular 6 even though no code has yet been written for it. We'll \n look at what it might do, and how to convince your manager to \n hold off on any new apps until it's released",
"voters": []
},
{
"id": 5,
"name": "Basics of Angular 4",
"presenter": "John Papa",
"duration": 2,
"level": "Beginner",
"abstract": "It's time to learn the basics of Angular 4. This talk \n will give you everything you need to know about Angular 4 to \n get started with it today and be building UI's for your self \n driving cars and butler-bots in no time.",
"voters": [
"bradgreen",
"igorminar"
]
}
]
}
为了显示最后的结果,我在 NodeJS 中使用了自定义路由,如下所示:
router.js:
var jsonServer = require('json-server')
const low = require('lowdb')
var server = jsonServer.create()
const db = low('db.json')
// Add custom routes before JSON Server router
server.get('/data/:id/sessions/:sessionId/voters/:voterName', function (req, res) {
// See https://github.com/typicode/lowdb
var user=db.get("sessions")
.find({id:sessionId})
.get("voters")
.find({voterName})
.value()
if (user) {
res.jsonp(user)
} else {
res.sendStatus(404)
}
})
server.use(function (req, res, next) {
if (req.method === 'POST') {
req.body.createdAt = Date.now()
}
// Continue to JSON Server router
next()
})
// Use default router
// server.use(router)
server.listen(3000, function () {
console.log('JSON Server is running')
})
但是当我运行这个命令时:
json-server --watch db.json --middlewares router.js
我收到以下错误:
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\node_modules\express\lib\application.js:210:11)
at createApp (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:79:9)
at load (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:148:13)
at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\utils\load.js:37:5)
at start (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:125:5)
at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:162:3)
at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\index.js:81:3)
at Object.<anonymous> (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\bin.js:3:14)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
提前感谢您的回答。
我认为你不应该使用 --middlewares 选项来启动你的服务器,router.js 不是中间件。所以在这里它尝试将您的 router.js 添加为中间件并且无法启动
你能试试吗:
json-server router.js --watch db.json
使用json服务器有两种选择,一种是运行通过你自己的js文件,另一种是通过运行你是运行的中间件js 文件你应该 运行 中间件这样 https://github.com/typicode/json-server#add-middlewares 只创建 module.export 如 link 所示。你不需要所有花哨的服务器东西。
我在使用自定义路由请求部署在 json-server 中的 db.json 时发现问题。
例如,对于下面给定的 json,我想按姓名访问选民,因此当我键入此内容时 url:
https://localhost:3000/data/1/sessions/:sessionId/voters/:voterName
其中sessionId
和voterName
是parameterized
,响应应该是{"voterName"}
db.json:
{
"id": 1,
"name": "Angular Connect",
"date": "2036-09-25T23:00:00.000Z",
"time": "10:00 am",
"price": 599.99,
"imageUrl": "/assets/images/angularconnect-shield.png",
"location": {
"address": "1057 DT",
"city": "London",
"country": "England"
},
"sessions": [
{
"id": 1,
"name": "Using Angular 4 Pipes",
"presenter": "Peter Bacon Darwin",
"duration": 1,
"level": "Intermediate",
"abstract": "Learn all about the new pipes in Angular 4, both \n how to write them, and how to get the new AI CLI to write \n them for you. Given by the famous PBD, president of Angular \n University (formerly Oxford University)",
"voters": [
"bradgreen",
"igorminar",
"martinfowler"
]
},
{
"id": 2,
"name": "Getting the most out of your dev team",
"presenter": "Jeff Cross",
"duration": 1,
"level": "Intermediate",
"abstract": "We all know that our dev teams work hard, but with \n the right management they can be even more productive, without \n overworking them. In this session I'll show you how to get the \n best results from the talent you already have on staff.",
"voters": [
"johnpapa",
"bradgreen",
"igorminar",
"martinfowler"
]
},
{
"id": 3,
"name": "Angular 4 Performance Metrics",
"presenter": "Rob Wormald",
"duration": 2,
"level": "Advanced",
"abstract": "Angular 4 Performance is hot. In this session, we'll see \n how Angular gets such great performance by preloading data on \n your users devices before they even hit your site using the \n new predictive algorithms and thought reading software \n built into Angular 4.",
"voters": []
},
{
"id": 4,
"name": "Angular 5 Look Ahead",
"presenter": "Brad Green",
"duration": 2,
"level": "Advanced",
"abstract": "Even though Angular 5 is still 6 years away, we all want \n to know all about it so that we can spend endless hours in meetings \n debating if we should use Angular 4 or not. This talk will look at \n Angular 6 even though no code has yet been written for it. We'll \n look at what it might do, and how to convince your manager to \n hold off on any new apps until it's released",
"voters": []
},
{
"id": 5,
"name": "Basics of Angular 4",
"presenter": "John Papa",
"duration": 2,
"level": "Beginner",
"abstract": "It's time to learn the basics of Angular 4. This talk \n will give you everything you need to know about Angular 4 to \n get started with it today and be building UI's for your self \n driving cars and butler-bots in no time.",
"voters": [
"bradgreen",
"igorminar"
]
}
]
}
为了显示最后的结果,我在 NodeJS 中使用了自定义路由,如下所示:
router.js:
var jsonServer = require('json-server')
const low = require('lowdb')
var server = jsonServer.create()
const db = low('db.json')
// Add custom routes before JSON Server router
server.get('/data/:id/sessions/:sessionId/voters/:voterName', function (req, res) {
// See https://github.com/typicode/lowdb
var user=db.get("sessions")
.find({id:sessionId})
.get("voters")
.find({voterName})
.value()
if (user) {
res.jsonp(user)
} else {
res.sendStatus(404)
}
})
server.use(function (req, res, next) {
if (req.method === 'POST') {
req.body.createdAt = Date.now()
}
// Continue to JSON Server router
next()
})
// Use default router
// server.use(router)
server.listen(3000, function () {
console.log('JSON Server is running')
})
但是当我运行这个命令时:
json-server --watch db.json --middlewares router.js
我收到以下错误:
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\node_modules\express\lib\application.js:210:11)
at createApp (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:79:9)
at load (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:148:13)
at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\utils\load.js:37:5)
at start (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:125:5)
at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:162:3)
at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\index.js:81:3)
at Object.<anonymous> (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\bin.js:3:14)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
提前感谢您的回答。
我认为你不应该使用 --middlewares 选项来启动你的服务器,router.js 不是中间件。所以在这里它尝试将您的 router.js 添加为中间件并且无法启动
你能试试吗:
json-server router.js --watch db.json
使用json服务器有两种选择,一种是运行通过你自己的js文件,另一种是通过运行你是运行的中间件js 文件你应该 运行 中间件这样 https://github.com/typicode/json-server#add-middlewares 只创建 module.export 如 link 所示。你不需要所有花哨的服务器东西。