0

我在节点中有一个脚本,我想自动重定向到我在一个数组中拥有的随机链接,页面是白色的,当我放置 maths.random 函数时不会重定向

有我的代码:

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 ...");

我想重定向到https://www.test.com/randomValueInMyArray

谢谢,本杰明

4

1 回答 1

0

我测试了你的代码,对我来说它工作得很好。

需要考虑两件事:你做一个

server.listen(4000);

但将“localhost:1337”打印到控制台。有点混乱;-)

另一件事是,您发送的 http 状态为301 Moved Permanently。这导致您的浏览器总是将您重定向到第一个请求的结果(即第一个随机值)。因为您说“永久”并且您的浏览器不会期望另一个值,如果它是永久的。

于 2019-04-11T14:31:49.293 回答