节点服务器中的随机路由

时间:2016-05-27 06:49:48

标签: javascript node.js express cron

我使用以下方法创建了一个服务器:

function randomString(length) {
    var result = '';
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    for (var i = length; i > 0; --i) 
        result += chars[Math.floor(Math.random() * chars.length)];
    return result;
}

var cron = require('node-cron');
var rString = randomString(12);
cron.schedule('15,30,45 * * * * *', function(){
    rString = randomString(12);
    app.get("/"+rString, function(req, res){
        //Whatever you need goes here.
        res.send("Yo"); 
    });
    console.log("Your random route is: localhost:3000/"+rString);
});

//Tried this too
/*app.get("/"+rString, function(req, res){
        //Whatever you need goes here.
        res.send("Yo"); 
});*/
console.log("Your random route is: localhost:3000/"+rString);

app.get("*",function(req,res){
   res.send("Sorry no link found!"); 
});

app.listen(3000);

我正在尝试每15秒为我的服务器生成新路由。当我将app.get放在cron作业中时,它根本就不会创建新的路径。第二,创建了初始路由,但是在更新rString时,它不会使初始路由无效并创建新路由。

1 个答案:

答案 0 :(得分:0)

我找到了办法。

var express = require("express");
var app = express();

function randomString(length) {
    var result = '';
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    for (var i = length; i > 0; --i) 
        result += chars[Math.floor(Math.random() * chars.length)];
    return result;
}

var cron = require('node-cron');
var rString = randomString(12);
cron.schedule('15,30,45 * * * * *', function(){
    rString = randomString(12);
    console.log("Your random route is: localhost:3000/"+rString);
});

console.log("Your random route is: localhost:3000/"+rString);
app.get("/:randomStr", function(req, res){
    if(req.params.randomStr === rString)
        res.send("Yo!")
    else
        res.send("Sorry no link found!");
});    
app.get("*",function(req,res){
    res.send("Sorry no link found!"); 
});

app.listen(3000);