Search code examples
javascripthtmlnode.jsurl-parametersquery-string

Redirect based on URL/Query Parameters


I basically just want to redirect the user to a different site based on the URL (or query) parameters but I have no idea how.

If the URL is https://www.tamoghnak.tk/redirect?link=https://www.tamoghnak.tk/gobob then it should redirect to https://www.tamoghnak.tk /gobob.

If the URL is https://www.tamoghnak.tk/redirect?link=https://stackoverflow.com then it should redirect to https://stackoverflow.com and so on (Redirect to any site in parameters).

How would I do this? (In Node, JS, HTML, etc.)


Solution

  • If you use Express it could be like this:

    const app = require('express')();
    
    app.get('/from', (req, res) => {
      // The optional first parameter to `res.redirect()` is a numeric
      // HTTP status.
      res.redirect(301, '/to');
    });
    app.get('/to', (req, res) => res.send('Hello, World!'));
    
    const server = await app.listen(3000);
    
    const res = await axios.get('http://localhost:3000/from'); // "Hello, World!" res.data;
    

    link https://masteringjs.io/tutorials/express/redirect

    All you have to do is take the parameter from the get request and paste its value into the redirect.

    My code:

    const app = require('express')();
    
    app.get('/from', (req, res) => {
      res.redirect(301, req.query.link);
    });