我试图用jsonschema来验证我的json。这是我的server.js代码:
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the port
var bodyParser = require('body-parser');
var methodOverride = require('method-override')
app.use(function(req, res, next) {
//the code hits this 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 with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);
routes.js看起来像这样:
module.exports = function (app) {
app.post('/api/postding', function (req, res) {
//do some schema validation
var test=1;
})
}
当我发布无效的json时,我现在收到此错误:
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)
问题是我如何才能为我的postrequest执行jsonschema验证?
答案 0 :(得分:1)
server.js
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the 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 this 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 with 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"});
})
}
正在使用我的电脑
当我通过REST Client发布{&#34; name:&#34; hoer&#34;}时,控制台输出
App listening on port 8080
{}
{"name:"hoer"}