I have a page that when you access it, it runs tests. I want my tests to run every week so Im trying to create a cron job that access my express route every week. Sort of like Im making a get request.
For testing sake I have a cron job that runs every 2 minutes:
//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',
});
});
If I go in my url to http://localhost:1337/my_page_route_name
It goes inside the router.get request just fine. But Is there a way I can trigger my cron job to call the same route and render the page every 2 minutes?
I’m unsure of how to do this because the router.get function uses res.render, and I have no res
variable in my cron job
{{ EDIT }}
My cron jobs works and triggers a POST request to my route:
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"
})
});
});
and i created an express route to receive the POST request;
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',
});
})
If I make a request in postman I can see the posr route returns the webpage html, but no scripts have been run, for example I have <script> document.querySelector('.breadcrumbs').append('[[ html loadded ]]') </script>
inside my html file that gets loaded, but the code doesnt seem to be ran in the response I recieve
Advertisement
Answer
Use a fetch package in node as http requests get pretty complicated quickly.
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',
});
});