节点js安排cron作业每周调用快速路由

node js schedule cron job to call express route every week

我有一个页面,当您访问它时,它 运行 正在测试。我希望我的测试每周 运行 所以我试图创建一个每周访问我的快速路线的 cron 作业。有点像我在发出获取请求。

为了测试,我有一个 cron 作业,每 2 分钟 运行s:


//schedule job every 2 minutes
schedule.scheduleJob("*/2 * * * *", function () {
    console.log('inside cron function')
});

router.get('/my_page_route_name', ensureAuthenticated, async function(req, res){
    res.render('my_page_route_file', {
        layout: 'dashboard.handlebars',
        jsMain: 'my_page_route_js',
    });
});

如果我进入 url 到 http://localhost:1337/my_page_route_name 它进入 router.get 请求就好了。但是有没有一种方法可以触发我的 cron 作业来调用相同的路由并每 2 分钟呈现一次页面?

我不确定如何执行此操作,因为 router.get 函数使用 res.render,而且我的 cron 作业

中没有 res 变量

{{ 编辑 }}

我的 cron 作业运行并触发了对我的路线的 POST 请求:

    schedule.scheduleJob("*/10 * * * *", async function() {
        console.log('inside cron function');

        const resp = await fetch("http://localhost:1337/my_page_route_name/", {
            "headers": {
                "content-type": "application/json"
            },
            "method": "post",
            "body": JSON.stringify({
                "username":"exvar",
                "password":"examplevar2"
            })
        });
    
    });

并且我创建了一条快速路由来接收 POST 请求;


router.post('/my_page_route_name', async function(req, res){
    

    res.render('my_page_route_name_html', {
        layout: 'dashboard.handlebars',
        jsMain: 'my_page_route_name_jsmain',
       
    });
})

如果我在邮递员中发出请求,我可以看到 posr 路由 returns 网页 html,但是没有脚本 运行,例如我有 <script> document.querySelector('.breadcrumbs').append('[[ html loadded ]]') </script> 在我的 html 文件中加载,但代码似乎不是 运行 在我收到的响应中

在节点中使用 fetch 包,因为 http 请求很快变得非常复杂。

const fetch = require('node-fetch');

//schedule job every 2 minutes
schedule.scheduleJob("*/2 * * * *", async function() {
    const response = await fetch('https://yourdomain.tld/my_page_route_name');
    const body = await response.json();

    console.log('inside cron function', body);
});

router.get('/my_page_route_name', ensureAuthenticated, async function(req, res){
    res.render('my_page_route_file', {
        layout: 'dashboard.handlebars',
        jsMain: 'my_page_route_js',
    });
});