javascript - How to call POST method in node.js service? -
i trying validate json jsonschema. server.js code:
// set ====================================================================== var express = require('express'); var app = express(); // create our app w/ express var port = process.env.port || 8080; // set port var bodyparser = require('body-parser'); var methodoverride = require('method-override') app.use(function(req, res, next) { //the code hits point! var data = ''; req.on('data', function(chunk) { data += chunk; }); req.on('end', function() { req.rawbody = data; }); console.log(data); next(); }); app.use(bodyparser.json()); app.use(methodoverride()); // routes ====================================================================== require('./routes.js')(app); // listen (start app node server.js) ====================================== app.listen(port); console.log("app listening on port " + port);
the routes.js looks this:
module.exports = function (app) { app.post('/api/postding', function (req, res) { //do schema validation var test=1; }) }
when post invalid json error now:
syntaxerror: unexpected token t <br> at object.parse (native) <br> at parse (c:\nodestuff\trystuff\node_modules\body-parser\lib\types\json.js:88:17) <br> at c:\nodestuff\trystuff\node_modules\body-parser\lib\read.js:108:18 <br> at done (c:\nodestuff\trystuff\node_modules\body-parser\node_modules\raw-body\index.js:233:14) <br> at incomingmessage.onend (c:\nodestuff\trystuff\node_modules\body-parser\node_modules\raw-body\index.js:279:7) <br> at incomingmessage.g (events.js:180:16) <br> at incomingmessage.emit (events.js:117:20) <br> at _stream_readable.js:943:16 <br> at process._tickcallback (node.js:419:13)
the question how can perform jsonschema validation postrequest?
server.js
// set ====================================================================== var express = require('express'); var app = express(); // create our app w/ express var port = process.env.port || 8080; // set port var bodyparser = require('body-parser'); var methodoverride = require('method-override') app.use(bodyparser.json()); app.use(bodyparser.urlencoded({extended: true})); app.use(function(req, res, next) { //the code hits point! var data = ''; req.on('data', function(chunk) { data += chunk; }); req.on('end', function() { req.rawbody = data; next(); }); console.log(data); }); app.use(methodoverride()); // routes ====================================================================== require('./routes.js')(app); // listen (start app node server.js) ====================================== app.listen(port); console.log("app listening on port " + port);
route.js
module.exports = function (app) { app.post('/api/postding', function (req, res) { console.log(req.body); console.log(req.rawbody); res.send({"test":"data"}); }) }
which working pc
when post {"name:"hoer"} through rest client, console output is
app listening on port 8080 {} {"name:"hoer"}
Comments
Post a Comment