Created
July 4, 2018 03:35
Improve middleware to support chunked request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const jsonServer = require('json-server') | |
const server = jsonServer.create() | |
const router = jsonServer.router('db.json') | |
const middlewares = jsonServer.defaults() | |
const util = require('util') | |
console.log("I am PingkungA") | |
// Set default middlewares (logger, static, cors and no-cache) | |
server.use(middlewares) | |
// Add custom routes before JSON Server router | |
server.get('/echo', (req, res) => { | |
res.jsonp(req.query) | |
}) | |
// To handle POST, PUT and PATCH you need to use a body-parser | |
// You can use the one used by JSON Server | |
server.use(jsonServer.bodyParser) | |
server.use((req, res, next) => { | |
console.log("========================"); | |
//var data = ''; | |
if ((req.method === 'POST') || (req.method === 'PATCH') || (req.method === 'PUT')) { | |
let body = []; | |
req.on('data', function(chunk) { | |
console.log("Received body data:"); | |
body.push(chunk); | |
}).on('end', function() { | |
//req.raw = Buffer.concat(body).toString(); | |
let data = Buffer.concat(body); | |
let schema = JSON.parse(data); | |
req.raw = schema; | |
console.log(req.raw); | |
req.body = req.raw; | |
console.log("Isarray : "+ Array.isArray(req.body)) | |
//console.log(util.inspect(req, {depth: null})); | |
if (req.method === 'POST') { | |
req.body.createdAt = Date.now() | |
} | |
//Get Request Body | |
console.log("req.body is " + req.body) | |
console.log("req.raw is " + req.rawBody) | |
}); | |
} | |
// Continue to JSON Server router | |
next() | |
}) | |
// Use default router | |
server.use(router) | |
server.listen(3000, () => { | |
console.log('JSON Server is running') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment