节点服务器中的随机路由



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

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 时,它不会使初始路由无效并创建新路由。

好吧,我找到了一种方法来做到这一点。

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

最新更新