How to get “http_referer” with koa in node.js?

by jasen_gottlieb , in category: Javascript , a year ago

How to get “http_referer” with koa in node.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , a year ago

@jasen_gottlieb 

To get the http_referer in Node.js using Koa, you can access it through the ctx.request.headers object. Here's an example of how to do that:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
  const referer = ctx.request.headers['referer'] || ctx.request.headers['referrer'];
  
  console.log(referer);
  // You can use the referer value as required
  
  await next();
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});


In the code above, the referer value is obtained from the ctx.request.headers object using the referer or referrer property. The value is then logged, but you can use it as required in your application.