简体   繁体   中英

Keeping connection alive in Javascript / XMLHttpRequest

Iam building an application that listens to an internal connection of a certain external url and insert its internally loaded content to a new page at my end.

My statement above might sound confusing but a good analogue of the external url are Instagram stories when you visit this external site, it loads complete in the browser (the rolling icon stops, but this doesn't stop the request of unseen updates )

I have built a JavaScript server using nodejs running on npm and have set the content header

Am also using htaccess to make it stay alive so that I can listen and load new internal connection

Header set Connection keep-alive>

but doesn't seems to work

    if(err){

        if(err == 'ENOENT'){
            res.writeHead(404, {'Content-Type' : 'text/html'});
            res.write(path.join(__dirname, 'public', '404.html'));
            res.end();

        }else{
            res.writeHead(500, {'Content-Type' : 'text/html'});
            res.write('<enter><h1>Some server error just occured .... </h1></center>');
            res.end();
        }

    }else{
        res.writeHead(200, {'Content-Type' : contentType, 'Connection':' keep-alive', 'Transfer-Encoding':' chunked', 'Accept':' */*', 'User-Agent':' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'});
        res.write(content);
        res.end();
    }

Am expecting to get the new loaded content each time a connection runs underground without reloading the browser and again just like scrolling through Instagram status / stories

I think this is the wrong approach. You could just have it check every 5 seconds to see if there is something new on the client side.

function checkURL(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.write(this.responseText);
        }
    };
    xhttp.open("GET", "https://example.com/", true);
    xhttp.send();
}
setInterval(checkURL,5000); //5000 = 5 seconds

If you must do it in Node.JS, take a look at this post: HTTP keep-alive in node.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM