Expressjs Sync/Asynchronous 中间件问题——如何解决?

Expressjs Sync/Asynchronous Middleware Issues -- How to fix?

我有一个 Expressjs 路由,它根据请求中的一些 JSON 正文参数执行 db INSERT(使用 Sequelize)。 bodyParser 中间件对正文执行 JSON 模式验证,如果未验证则 returns 出错。

这里的问题是 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}));
        }
    }
};

你的中间件调用 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) { ... });