1

我有一个 Expressjs 路由,它基于请求中的一些 JSON Body 参数执行 db INSERT(使用 Sequelize)。中间件对bodyParser主体进行 JSON 模式验证,如果未验证则返回错误。

这里的问题是其中的某些bodyparser内容正在异步执行,并且我遇到了错误,例如将空值插入数据库(即使在验证失败之后)和Headers already returned to client错误。

如何最好地解决这个问题?

路线:

var bodyParser = json_validator.with_schema('searchterm');
router.post('/', bodyParser, function (req, res, next) {
    Searchterm.findOrCreate({
        where: {searchstring: req.body.searchstring},
        defaults: {funnystory: req.body.funnystory},
        attributes: ['id', 'searchstring', 'funnystory']
    }).spread((searchterm, created) => {
        if (created) {
            res.json(searchterm);
        } else {
            res.sendStatus(409);
        }
    }).catch(next);
});

中间件:

var ajv = new Ajv({allErrors: true});
var jsonParser = bodyParser.json({type: '*/json'});

module.exports.with_schema = function(model_name) {
    let schemafile = path.join(__dirname, '..', 'models', 'schemas', model_name + '.schema.yaml');
    let rawdata = fs.readFileSync(schemafile);
    let schema = yaml.safeLoad(rawdata);
    var validate = ajv.compile(schema);
    return function(req, res, next) {
        jsonParser(req, res, next);
        if (!validate(req.body)) {
            res.status(400).send(JSON.stringify({"errors": validate.errors}));
        }
    }
};
4

1 回答 1

0

您的中间件调用next过早;改变:

return function(req, res, next) {
    jsonParser(req, res, next);
    if (!validate(req.body)) {
        res.status(400).send(JSON.stringify({"errors": validate.errors}));
    }
}

到:

return function(req, res, next) {
    if (!validate(req.body)) {
        res.status(400).send(JSON.stringify({"errors": validate.errors}));
    }
}

以及您的路线定义:

router.post('/', jsonParser, bodyParser, function (req, res, next) { ... });
于 2018-12-17T21:55:30.780 回答