javascript – Connect to a site using JS?

Question:

Good mood to you all.

there is a site.ru/test.php in the file test.php number 1 written and there is nothing else in it .

How can I connect to this page in JS and get its content into a variable without opening the page itself in a browser window ?

Answer:

One of the most modern ways to make such a request is with the Fetch API :

fetch('http://httpbin.org/get?param=value')
  .then((response) => response.json())
  .then(data => console.log(data));
fetch('http://httpbin.org/get?param=value')
  .then(function (response) {
    return response.text();
  })
  .then(function(data) {
    console.log(data);
  });

Support in browsers (IE / Safari) is not very good yet, but the presence of working polyfills allows you to indulge in this pleasure.


It's also worth mentioning that I chose httpbin.org for this demonstration for a reason. It allows cross-domain requests (CORS) by sending a pair of headers in the response:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:null

Without this, the browser would not allow javascript to receive a response from a site with a domain other than the one on which the script is running.
This security policy was designed to prevent malicious scripts from accessing services on your behalf that they do not own.

Scroll to Top