0

I have one script in node, and i want to automatically redirect to randoms links that i have in one array, the page is white and doesn't redirect when i put the maths.random function

There is my code :

const http = require('http');

let randURLs = [
    "aaaaa",
    "xxxxx",
    "bbbbb"
];
const server = http.createServer(function(req, res) {
    if (req.method === 'POST') {
       console.log('post method')
    }
    else {
        let randNumber = Math.floor(Math.random()*randURLs.length);
        res.writeHead(301,{Location: 'https://www.test.com/' + 
randURLs[randNumber]});
     }
    res.end();
});

server.listen(4000);
console.log("localhost:1337 ...");

I want to redirect to https://www.test.com/randomValueInMyArray

Thanks, Benjamin

Benjamin Barbé
  • 281
  • 2
  • 4
  • 16

1 Answers1

0

I tested your code and for me it works perfectly fine.

two things to consider: You do a

server.listen(4000);

but printing "localhost:1337" to the console. A little bit confusing ;-)

Another thing is, that you send a http status of 301 Moved Permanently. That leads to the effect that your browser always redirects you to the result of the first request (i.e. the first random value). Because you said "permanently" and your browser doesn't expect another value if it's permanent.

Florian Schlag
  • 639
  • 4
  • 16
  • hello @florian, thanks fior u time, so what i have to do to not always redirects to the first random value? – Benjamin Barbé Apr 11 '19 at 14:34
  • Have a look on this answer: https://stackoverflow.com/a/4062281/8745384 (http 302 RFC is here: https://tools.ietf.org/html/rfc7231#section-6.4.3) Basically it tells the client that "[...] the redirection might be altered on occasion [...]" – Florian Schlag Apr 11 '19 at 14:36