What is the referer

Referer in Chinese means: reference page, reference page.

The figure below will be intuitive,(the better we understand you, the better we understand you

Direct access to the

If there is a referer, it is being referenced, either from an HTML page, via CSS @import, or through background(URL).

Get reffer

console.log(req.headers['referer']); // Must be lowercaseCopy the code

Matters needing attention

  • The keyword must be lowercase
  • In the old browser, the keyword isreferRather thanreferer

Application: Reffer anti-theft chain

Design ideas

We can verify that the resource request is from another site by comparing req.headers[‘referer’] with host in req.url.

Then, when we know the source of the resource request, we can decide whether and how to respond to the request through a number of means.

The usual approach is to set up a whitelist, within which we respond to requests, otherwise we don’t.

The source code

let http = require('http');
let fs = require('fs');
let url = require('url');
let path = require('path');
const whiteList = [
'localhost:8080'
// ,'192.168.0.22'
];

let server = http.createServer(function(req,res){
let refer = req.headers['referer']||req.headers['refer'];

if(refer){
  let referHostName = url.parse(refer,true).host;
  let currentHostName = url.parse(req.url,true).host;

  if(referHostName ! = currentHostName && whiteList.indexOf(referHostName) == -1){ res.setHeader('Content-Type'.'text/html; charset=utf-8');
    res.end('Your doll stole a chain! '); // If it is an image resource request, it is invalid to return text like thisreturn ;
  }
}

res.setHeader('Content-Type'.'image/png');
fs.createReadStream(path.join(__dirname,'2.jpg')).pipe(res);
}).listen(9999);
Copy the code