Node - Tell origin of request

后端 未结 2 1214
南方客
南方客 2021-02-04 05:02

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

相关标签:
2条回答
  • 2021-02-04 05:10

    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

    0 讨论(0)
  • 2021-02-04 05:14

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

    app.use(function(req, res, next) {
        //var origin=req.headers.origin
        next();
    });
    
    0 讨论(0)
提交回复
热议问题