我想用jsonschema来验证我的json。这是我的server.js代码:如何在node.js服务中调用POST方法?
// 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验证?
尝试移动'app.use(bodyParser.js on());'var methodoverride ...'下面的正下方' –
为什么你在读取整个原始请求而不是让'bodyParser.json()'处理请求数据? – mscdex
我想收到原始的请求,所以我可以在我的post方法中执行jsonschema验证 – Pindakaas