我有一个快递应用程序,它有一个 post 方法(post 是 json 类型):
server.js(简化版):
app.post('/listener/v1/event/', function(req, res) {
.
.
var event = req.body;
var validator = require("./validator");
validator.validate(event);
}
validator.js 包含对 json 的验证:
var jsonschemavalidate = require("json-schema");
var basicSchema = require('fs').readFileSync('./schema.json', 'utf8');
exports.validate = function (event) {
console.log(jsonschemavalidate.validate(event, basicSchema).errors);
}
schema.json:
{
name : "test",
type : 'object',
properties : {
event_id : { type : 'string' },
timestamp : { type : 'string' }
}
}
对于我使用 curl 的输入:
curl -i -X POST -H 'Content-Type: application/json' -d '{"event_id": "NedaleGassss", "timestamp": "a2009321"}' http://localhost:3000/listener/v1/event/
输出如下:
[ { property: '',
message: 'Invalid schema/property definition {\n name : "test",\n type : "object",\n additionalProperties : false,\n properties :\n {\n event_id : { type : "string" },\n timestamp \t: { type : "string" }\n }\n}' } ]