Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.com or someothersite.com. 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.

like image 931
Nicola Peluchetti Avatar asked Aug 28 '13 21:08

Nicola Peluchetti


People also ask

How do I get node JS origin request?

Get the Request Origin from the Origin headerconst origin = req. headers. origin; });

How do I get a domain name in node?

By using the URL class, a built-in module of Node. js, we can easily extract domain/hostname and protocol from a given url without using any third-party package.

What does json () do in Express?

json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.

What is a get request in Express?

GET requests are used to send only limited amount of data because data is sent into header while POST requests are used to send large amount of data because data is sent in the body. Express. js facilitates you to handle GET and POST requests using the instance of express.


1 Answers

You have to retrieve it from the HOST header.

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

It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.


If this is for supporting cross-origin requests, you would instead use the Origin header.

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

Note that some cross-origin requests require validation through a "preflight" request:

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; 
  • message.socket.
  • socket.remoteAddress

Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.

like image 64
Jonathan Lonowski Avatar answered Sep 24 '22 10:09

Jonathan Lonowski