Loopback 从操作钩子中获取 IP 地址
Loopback get IP address from operation hook
好吧,那个 XD,我如何从操作挂钩中获取查询器的 IP 地址(如果它甚至是单词 xD)?还是远程挂钩? (我可以用loopback.getCurrentContext()
保存起来用在操作挂钩上)
说:
Model.observe('loaded', function(ctx,next) {
ctx.ip ??
});
所以我发现了这个:https://github.com/strongloop/loopback/issues/1495 & this: How to determine a user's IP address in node
两者都提供了很大的帮助,我只是获取了获取地址所需的内容并将其保存在环回当前上下文中,就像在启动脚本中这样:
var loopback = require('loopback');
module.exports = function (app) {
app.remotes().before('*.*', function(ctx,next) {
loopback.getCurrentContext().set('remoteAddress',ctx.req.connection.remoteAddress);
next();
});
app.remotes().before('*.prototype.*', function(ctx,instance,next) {
loopback.getCurrentContext().set('remoteAddress',ctx.req.connection.remoteAddress);
next();
});
};
然后我就这样在一个操作钩子上获取它:
Model.observe('loaded', function(ctx,next) {
console.log("Remote Address: ", loopback.getCurrentContext().get('remoteAddress'));
});
环回 3 更新:您可以使用此 属性 获取 IP 地址:
ctx.req.connection.remoteAddress
您还应该在 server.js 中添加此代码以授予真实 ip,否则您将获得负载均衡器 IP:
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);
不是真正问的问题,但是当你需要远程方法中调用者的 ip 地址,并且你的 nodejs 已经在 Apache 代理(或配置良好的 nginx 代理)后面时,你可以简单地
const ip = req.header('X-Forwarded-For')
获取IP地址。
您可以使用以下命令获取请求用户的 IP 地址。
var ipAddress = context.req.connection.remoteAddress
好吧,那个 XD,我如何从操作挂钩中获取查询器的 IP 地址(如果它甚至是单词 xD)?还是远程挂钩? (我可以用loopback.getCurrentContext()
保存起来用在操作挂钩上)
说:
Model.observe('loaded', function(ctx,next) {
ctx.ip ??
});
所以我发现了这个:https://github.com/strongloop/loopback/issues/1495 & this: How to determine a user's IP address in node 两者都提供了很大的帮助,我只是获取了获取地址所需的内容并将其保存在环回当前上下文中,就像在启动脚本中这样:
var loopback = require('loopback');
module.exports = function (app) {
app.remotes().before('*.*', function(ctx,next) {
loopback.getCurrentContext().set('remoteAddress',ctx.req.connection.remoteAddress);
next();
});
app.remotes().before('*.prototype.*', function(ctx,instance,next) {
loopback.getCurrentContext().set('remoteAddress',ctx.req.connection.remoteAddress);
next();
});
};
然后我就这样在一个操作钩子上获取它:
Model.observe('loaded', function(ctx,next) {
console.log("Remote Address: ", loopback.getCurrentContext().get('remoteAddress'));
});
环回 3 更新:您可以使用此 属性 获取 IP 地址:
ctx.req.connection.remoteAddress
您还应该在 server.js 中添加此代码以授予真实 ip,否则您将获得负载均衡器 IP:
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);
不是真正问的问题,但是当你需要远程方法中调用者的 ip 地址,并且你的 nodejs 已经在 Apache 代理(或配置良好的 nginx 代理)后面时,你可以简单地
const ip = req.header('X-Forwarded-For')
获取IP地址。
您可以使用以下命令获取请求用户的 IP 地址。
var ipAddress = context.req.connection.remoteAddress