0

I have a back-end by nodejs I need to know where user come from. if he came from localhost (postman) or his website HTTP request. I need to know his user domain's not mind like 'http://localhost/' or 'http://user-website.com' or even from google search ! from he is came ?

, I tried user req.get('origin) but always return undefined

Mahmoud Niypoo
  • 1,598
  • 5
  • 24
  • 41

3 Answers3

1

You must connect 'url' module

var http = require('http');
var url = require('url') ;

http.createServer(function (req, res) {
  var hostname = req.headers.host; // hostname = 'localhost:8080'
  var pathname = url.parse(req.url).pathname; // pathname = '/MyApp'
  console.log('http://' + hostname + pathname);

  res.writeHead(200);
  res.end();
}).listen(8080);
0

use req.headers['user-agent'] to see if it is postman agent or not.

Rishabh Rawat
  • 849
  • 6
  • 11
  • it's give me a browser "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36" – Mahmoud Niypoo Mar 23 '19 at 11:49
0

In order to know whether the request is coming from localhost or a remote client, you'll need to obtain the client's IP address. Example in Express:

app.get('/', (req, res) => {
  const ipAddress = req.connection.remoteAddress;
  // ...
});

More docs about getting the IP here, also check this other question on the subject.

Basically if the request is coming from localhost, ipAddress will be ::1 or other localhost IP address, but if it's not, it's going to look like a public IP address, like 173.194.79.101 (the IP of google.com).

Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
  • thanks but it's give that "::ffff:169.254.8.129" to me from localhost and postman ! isn't there any way or third part package give me a domain name ? – Mahmoud Niypoo Mar 23 '19 at 12:34
  • I found this solution req.header('Referer') this give to ma the previous page is this is best answer ? – Mahmoud Niypoo Mar 23 '19 at 13:15
  • 1
    No, referer can be spoofed, and it's an optional field. it's a bad idea to use if – Nino Filiu Mar 23 '19 at 13:55
  • You can use [dns.reverse](https://nodejs.org/api/dns.html#dns_dns_reverse_ip_callback) to resolve the IP address to a hostname – Nino Filiu Mar 23 '19 at 13:56
  • I'm trying dns.reverse but it's always give to me `{"errno":"ENOTFOUND","code":"ENOTFOUND","syscall":"getHostByAddr","hostname":"::ffff:169.254.8.129"}` – Mahmoud Niypoo Mar 23 '19 at 14:45
  • That's valid behavior. You should only reverse-DNS `69.254.8.129`. It should point to `c-69-254-8-129.hsd1.ga.comcast.net.`. – Nino Filiu Mar 23 '19 at 21:29
  • By the way, you should handle cases where reverse DNS resolution doesn't find any hostname - every hostname has an IP, but not every IP is linked with a hostname! The [wikipedia page for DNS](https://en.wikipedia.org/wiki/Domain_Name_System) can be helpful to understand why. – Nino Filiu Mar 23 '19 at 21:30