L
L
lexstile2018-10-30 13:57:06
JavaScript
lexstile, 2018-10-30 13:57:06

How to send an asynchronous request from localhost to an external site in pure JS?

There is an asynchronous request:

getData = (url, type='GET', async=true) => {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open(type, url, async);
            
            /*xhr.setRequestHeader('Content-type', 'text/html');
            xhr.setRequestHeader('Accept', 'application/json');
            xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
            xhr.setRequestHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            xhr.setRequestHeader("Access-Control-Max-Age", "3600");
            xhr.setRequestHeader("Access-Control-Allow-Headers", "x-requested-with"); */

            xhr.onprogress = (event) => {
                console.log( 'Получено ' + (event.loaded / 1024).toFixed(3) + ' Кбайт за ' + (event.timeStamp / 1000).toFixed(3) + ' секунд');
            }
            xhr.onload = () => {
                if (xhr.status === 200) {
                    resolve({
                        data: JSON.parse(xhr.responseText),
                        status: xhr.status
                    }); 
                } else {
                    reject({
                        error: xhr.statusText,
                        status: xhr.status
                    });
                }

            }
            xhr.onerror = () => {
                reject({
                    error: xhr.statusText ? xhr.statusText : 'Не удалось выполнить запрос',
                    status: xhr.status
                });
            }
            xhr.send();
        });
    }

Directly from the localhost CORS does not let.
If through https://cors-anywhere.herokuapp.com/ - it works every other time (it's not clear why).
I read that you need to add a pre-request with OPTIONS, but I don’t know how to do this and with what headers.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
dollar, 2018-10-30
@dollar

You can create a browser extension and allow it to access any sites.
And also teach the extension to communicate with localhost. It's not hard.

T
tyzberd, 2018-10-30
@tyzberd

Read here https://learn.javascript.ru/xhr-crossdomain
And the headers must be on a side server.

P
profesor08, 2018-10-30
@profesor08

fetch

let json = await (await fetch("https://www.google.ru/", {
  mode: "no-cors"
})).json();

console.log(json);

But the server must return the Access-Control-Allow-Origin: * header, where * means that access is from any domains, or instead of * it can be the name of your domain to restrict access only for it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question