【问题标题】:Expressjs Sync/Asynchronous Middleware Issues -- How to fix?Expressjs 同步/异步中间件问题——如何解决?
【发布时间】:2018-12-17 20:49:39
【问题描述】:

我有一个 Expressjs 路由,它根据请求中的一些 JSON 正文参数执行 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}));
        }
    }
};

【问题讨论】:

    标签: javascript express sequelize.js jsonschema ajv


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-10-14
      • 2021-03-27
      • 1970-01-01
      • 2019-03-27
      • 2019-02-13
      • 2018-11-10
      • 2016-11-08
      • 1970-01-01
      • 2020-02-22
      相关资源
      最近更新 更多