添加一個默認值模型,這是我的模型如何從功能Sailsjs
module.exports = {
attributes: {
ip: {
type: 'ip'
},
useragent: {
type: 'text'
},
type: 'int'
}
}
};
所以我需要的是創建記錄之前,我需要的IP地址和用戶代理從自動填入請求進來
這可行嗎?
謝謝
添加一個默認值模型,這是我的模型如何從功能Sailsjs
module.exports = {
attributes: {
ip: {
type: 'ip'
},
useragent: {
type: 'text'
},
type: 'int'
}
}
};
所以我需要的是創建記錄之前,我需要的IP地址和用戶代理從自動填入請求進來
這可行嗎?
謝謝
是的,你可以用Lifecyclecallbacks做到這一點(見:http://sailsjs.org/#/documentation/concepts/ORM/Lifecyclecallbacks.html)
module.exports = {
attributes: {
ip: {
type: 'ip'
},
useragent: {
type: 'text'
},
},
// Lifecycle Callbacks
beforeCreate: function (values, cb) {
values.ip = <SET IP>
values.useragent = <SET USER AGENT>
cb();
});
};
您可以通過設置req.options
一些屬性通過帆policy做到這一點。如果你有一個User
模型,並使用藍圖create
路線,然後在你的配置/策略你必須:
UserController: {
create: 'setValues'
}
和API /政策/ setValues.js:
module.exports = function(req, res, next) {
req.options.values = req.options.values || {};
req.options.values.ip = <SET IP>;
req.options.values.agent = <SET USER AGENT>;
return next();
};
我不記得獲取用戶IP的首選方式,但this question看起來很有希望。對於用戶代理,您可以嘗試req.headers['user-agent']
。
如果您使用自定義控制器操作而不是藍圖,這仍然可以正常工作,您只需將與請求一起傳遞的值與req.options.values
合併即可。
我特別說:「我需要從REQUEST獲取值,我不想手動填充值 – Sahan 2014-09-25 12:01:03