How to access client IP address in Meteor? [duplicate]

主宰稳场 提交于 2019-11-30 13:43:23

As Florin mentioned, this is all pretty much integrated with Meteor now, as opposed to the dark ages when we had to do it ourselves. However, I've additionally wrapped it in a package that tracks all open connections and allows you to query for their IPs: https://github.com/mizzao/meteor-user-status. It also does a bunch of other useful stuff.

Getting the client IP:

Without a http request, in the functions you should be able to get the clientIP with:

clientIP = this.connection.clientAddress;
//EX: you declare a submitForm function with Meteor.methods and 
//you call it from the client with Meteor.call().
//In submitForm function you will have access to the client address as above

With a http request and using iron-router and its Router.map function:

In the action function of the targeted route use:

clientIp = this.request.connection.remoteAddress;

On client

headers = {
    list: {},
    get: function(header, callback) {
        return header ? this.list[header] : this.list;
    }
}

Meteor.call('getReqHeaders', function(error, result) {
    if (error) {
        console.log(error);
    }
    else {
        headers.list = result;
    }
});

On server:

headers = {
    list: {},
    get: function(header) {
        return header ? this.list[header] : this.list;
    }
};

var app = typeof WebApp != 'undefined' ? WebApp.connectHandlers : __meteor_bootstrap__.app;
app.use(function(req, res, next) {
    reqHeaders = req.headers;
    return next();
});

Meteor.methods({
    'getReqHeader': function(header) {
        return reqHeaders[header];
    },
    'getReqHeaders': function () {
        return reqHeaders;
    },
});

You can use this package: https://github.com/gadicohen/meteor-headers. It gets headers on both client and server.

If you want to do it without a package, you can 'inspire' yourself from the code above, the thing to remember is that prior to 0.6.5 we used the 'hidden' __meteor_bootstrap__.app and post 0.6.5 it's recommended to use WebApp.connectHandler instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!