简体   繁体   中英

How to protect a route with a referrer in Node.js

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM