0

I am trying to protect a route in my node.js application such that if the user wants to go to the page /post they have to come from /blog. If the user comes from anything other than /blog they are to be redirected to /. I have the following code that uses the http referrer

let ref = req.headers.referer;

if ((ref === undefined) || (!ref.includes('blog'))) {
  res.redirect('/')
}  

It seems to work well if I console.log for testing but if I do res.redirect, I get the error

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client.

How can I use the referrer to protect the route.

Should there be any other way of accomplishing this without using referring: all suggestions are welcome.

Thanks in advance

Koos
  • 117
  • 4
  • 15
  • 2
    That error means you're placing that code *after* calling `res.send()` or a similar command instead of before. –  Feb 12 '20 at 14:49
  • 1
    Does this answer your question? [ERR\_HTTP\_HEADERS\_SENT: Cannot set headers after they are sent to the client](https://stackoverflow.com/questions/52122272/err-http-headers-sent-cannot-set-headers-after-they-are-sent-to-the-client) – Milan Velebit Feb 12 '20 at 14:49
  • @koos, basically referer will return only full path then how you will check using includes – R.G.Krish Feb 12 '20 at 14:58

1 Answers1

0

Try this, In your app.js file include this.

const express = require('express');
const app = express();

app.get('/',(req, res, next)=>{
  res.send('Ready')
});

app.get('/test',(req, res, next)=>{
  res.send('Ready')
});

// Below (*) will consider unwanted urls
app.use('/*', function(req, res, next) {
  res.redirect('/')
});


app.listen(4000);

FYI, If you try demo.com/unkownurl will redirect to root like demo.com/

R.G.Krish
  • 487
  • 5
  • 22