Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node - Tell origin of request

Is it possible to tell the difference between a request coming directly from a URL in a browser vs. a resource being called from a remote web page?

For example, I would like to serve a web page when someone visits my URL directly (types in http://mywebsite.com) in a web browser, but when a user calls a resource on my app via a url from a seperate domain (like <img src='http://mywebsite.com' />) then I'd like to serve different content.

I've looked in the request and in the headers but it looks the same regardless of

like image 617
Joe Longstreet Avatar asked Aug 09 '12 01:08

Joe Longstreet


People also ask

How do you find the origin of a request?

The origin is determined by the URL of the HTML document, not the script.

How do I find my URL for Origin Express?

To get the domain originating the request in Express. js, we can use req. get with the 'host' or 'origin' header string. const host = req.

What is req originalUrl?

The req.originalUrl property is much like req.url however, it retains the original request URL thereby allowing you to rewrite req.url freely for internal routing purposes.


2 Answers

I think you are looking for the referer string in the request.header.

So the simple version would look like this:

http.createServer(function (req, res) {
  var ref = req.headers.referer;

  if(ref) {
    // serve special content
  }
  else {
    // serve regular homepage
  }
}).listen(1337, '127.0.0.1');

edited the answer to reflect the input from anu below - it should be referer

like image 156
Gates VP Avatar answered Oct 19 '22 17:10

Gates VP


In middleware you have to use this way "req.headers.origin"

app.use(function(req, res, next) {
    //var origin=req.headers.origin
    next();
});
like image 22
Imdadul Huq Naim Avatar answered Oct 19 '22 18:10

Imdadul Huq Naim