How do I get the domain originating the request in express.js?

I'm using express.js and I need to know the domain which is originating the call. This is the simple code

app.get(
'/verify_license_key.json',
function( req, res ) {
// do something

How do I get the domain from the req or the res object? I mean I need to know if the API was called by somesite.example or someothersite.example. I tried doing a console.dir of both req and res but I got no idea from there, also read the documentation but it gave me no help.

161517 次浏览

你必须从 HOST取回它。

var host = req.get('host');

在 HTTP 1.0中它是可选的,但是在1.1中是必需的。而且,应用程序总是可以强加一个自己的需求。


如果这是为了支持 跨来源请求,那么您应该使用 Origin头。

var origin = req.get('origin');

注意,有些跨原点请求需要通过 飞行前请求进行验证:

req.options('/route', function (req, res) {
var origin = req.get('origin');
// ...
});

If you're looking for the client's IP, you can retrieve that with:

var userIP = req.socket.remoteAddress;

请注意,如果您的服务器位于代理的后面,这可能会提供代理的 IP。能否获得用户的 IP 取决于代理传递的信息。但是,它通常也会出现在标题中。

Instead of:

var host = req.get('host');
var origin = req.get('origin');

你亦可使用:

var host = req.headers.host;
var origin = req.headers.origin;

在 Express 4.x 中,你可以使用返回域名的 req.hostname,不带端口。例如:

// Host: "example.com:3000"
req.hostname
// => "example.com"

See: http://expressjs.com/en/4x/api.html#req.hostname

req.get('host') is now deprecated, using it will give Undefined.

使用,

    req.header('Origin');
req.header('Host');
// this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.

2022年,我使用 Express v4.17.1 get 得到以下结果

Var host = req.get (‘ host’) ;//works,localhost: 3000

Var host = req.headers.host;//works,localhost: 3000

Var host = req.hostname;//works,localhost

Var source = req.get (‘ source’) ;//不工作,未定义

Var source = req.headers.source;//not work,unDefinition

enter image description here