我有一个express应用,它有一个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}' } ]发布于 2014-02-25 04:23:31
正如错误所述,您的架构无效。模式也应该是有效的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');https://stackoverflow.com/questions/13002898
复制相似问题