我有一个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}' } ]
最佳答案
正如错误所示,您的架构无效。模式也应该是有效的 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');
关于json - Nodejs json-schema 无法读取架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13002898/