简体   繁体   中英

Access req.headers in beforeCreate

我需要获取一些头“用户代理”以及IP地址,如何从beforeCreate内进行操作?

The req object is not available in waterline. So the next question is if your using blueprints.

If Yes, then you can doo like forrestranger suggests, but I think its better fit for a policy than over complicating it with middleware.

This is an example where I check for a companyId on every query.

// policy.js
module.exports = function(req, res, next) {
    req.options.where = _.assign({companyId : req.session.user.company.id}, req.options.where);
    req.query.companyId = req.session.user.companyId;
    return next();
};

If NO, then just attach the necessary info when you run your own create statement in the controller.

I would add a check in my beforeCreate that makes sure those fields are present as a form of self checking.

Assuming Sails 0.10, I don't think that's possible in beforeCreate just from digging through the waterline source code.

An alternative to that might be to have some middleware that attaches whatever info you need to the body so that it's available in beforeCreate and then removing it before you call next() so it doesn't cause your model validation to fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM