简体   繁体   中英

Get IP address from request object in Meteor

I want to retrieve the client's IP address before I redirect the client to an external URL.

Here is my code:

Router.route('/:_id', {name: 'urlRedirect', where: 'server'}).get(function () {
    var url = Urls.findOne(this.params._id);
    if (url) {
        var request = this.request;
        var response = this.response;
        var headers = request.headers;
        console.log(headers['user-agent']);
        this.response.writeHead(302, {
            'Location': url.url
        });
        this.response.end();
    } else {
        this.redirect('/');
    }
});

My question is: Can I get the IP address from the request object?

According to the Iron-Router guide , the request you get from this.request will be a typical NodeJS request object:

Router.route('/download/:file', function () {
  // NodeJS request object
  var request = this.request;

  // NodeJS  response object
  var response = this.response;

  this.response.end('file download content\n');
}, {where: 'server'});

So you should be able to loop the IP address up in this.request.connection.remoteAddress .

As stated in this answer , you may also have to look in this.request.headers['x-forwarded-for'] in some cases.

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