By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Node.JS How to properly make xhttp request to url every 20secs using node js


New Coder
Hello house, i am new to node js and i needed to run a task that makes an xhttp request to a given url every 20 secs.

So my hosting cpanel i saw nodejs setup, and after few clicks i got the setup running and the customer care for my hosting company said my nodejs setup was correct and running perfectly.
However am not getting the effect of the running as the expected xhttp request to the specific url is not working.
in my nodejs directory i created a file called NAME.js
And inside this NAME.js it has this simple code in it.
// NAME.js
var play = setInterval(function(){
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "http://mydomain/process.php");
        xhr.setRequestHeader("Content-Type", "application/text");
    }, 2000);

but this effect is not working as the process.php file is not getting any post to it every 20 secs
the code you provided uses the XMLHttpRequest object, which is used to make HTTP requests from a web browser.

If you want to make HTTP requests from a Node.js script, you will need to use a different library. There are several options available, but a popular choice is the request library. You can install it by running the following command in your terminal:

npm install request

Once you have installed the request library, you can use it to make HTTP requests from your Node.js script like this:

const request = require('request');

setInterval(function() {
    url: 'http://mydomain/process.php',
    body: 'justtext',
    headers: {
      'Content-Type': 'application/text'
  }, function(error, response, body) {
    // handle the response
}, 2000);

This code will make a POST request to the specified URL every 20 seconds.

New Threads

Latest posts

Buy us a coffee!

Top Bottom