我有一个快速应用程序,它有一个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}' } ]
答案 0 :(得分:0)
您的架构无效,正如错误所示。架构也应该是有效的JSON, 所以属性和字符串应该是双引号:
{
"name" : "test",
"type" : "object",
"properties" : {
"event_id" : { "type" : "string" },
"timestamp" : { "type" : "string" }
}
}
这应该可以解决问题,(除非你在过去一年中已经弄明白了)
还有:
var basicSchema = require('fs').readFileSync('./schema.json', 'utf8');
可能会被替换为:
var basicSchema = require('./schema');