我需要知道用户来自节点js

时间:2019-03-23 09:15:08

标签: node.js

我有一个nodejs后端,我需要知道用户来自哪里。 如果他来自本地主机(邮递员)或他的网站HTTP请求。 我需要知道他的用户域不像“ http://localhost/”或“ http://user-website.com”,甚至不是来自Google搜索!从他来吗?

,我尝试了用户req.get('origin),但始终返回undefined

3 个答案:

答案 0 :(得分:1)

您必须连接“ URL”模块

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);

答案 1 :(得分:0)

使用req.headers['user-agent']来查看它是否是邮递员代理。

答案 2 :(得分:0)

为了知道请求是来自localhost还是远程客户端,您需要获取客户端的IP地址。 Express中的示例:

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

有关获取IP here的更多文档,请同时查看this other question on the subject

基本上,如果请求来自localhost,则ipAddress将是::1或其他localhost IP address,但如果不是,它将看起来像一个公共IP地址,例如173.194.79.101(google.com的IP)。

相关问题