T
T
TCloud2021-04-28 17:47:38
JavaScript
TCloud, 2021-04-28 17:47:38

What is the correct way to make a cross-domain request via fetch()?

Hello!

There is a task to receive a file under the link, using JavaScript. I'm trying to fetch a file via fetch(), example below. The problem is that when requesting a file by reference, a third-party server returns an error:

Access to fetch at 'ссылка на сторонний сервис' (redirected from 'ссылка на файл') 
from origin 'домен с которого делается запрос' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


And the most interesting thing is that when calling fetch () under your subdomain, an error occurs, and everything is OK with a colleague (under his subdomain). Below I have attached a list of headers of two requests, one is mine, the other is a colleague.
I hope there are experts who can explain why "my fetch" and "my colleague's fetch" work differently.

Request code:
fetch('поддомен.домен.ru/файл')
    .then(response => response.text())
    .then(data => console.log(data))


Request headers:

My request:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,ru;q=0.8,ja;q=0.7,pl;q=0.6,tr;q=0.5
Cache-Control: no-cache
Connection: keep-alive
DNT: 1
Host: other.host.com
Origin: https://sub1.domain.ru
Pragma: no-cache
Referer: https://sub1.domain.ru/
sec-ch-ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.3


Colleague request:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: no-cache
Connection: keep-alive
Cookie: bla-bla-bla-длинная-строка
Host: sub2.domain.ru
Pragma: no-cache
Referer: https://sub2.domain.ru/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"
sec-ch-ua-mobile: ?0
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Askhat Bikmetov, 2021-04-28
@OTCloud

The server to which you are making the request must return the Access-Control-Allow-Origin header in the response, the value of which contains the URL of the application that actually makes the request
. For example:

Access-Control-Allow-Origin: http://localhost:3000, https://example.com

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question