Проблемы с Cors — это боль, особенно если ваш сервер разрешает все, но fetch все равно выдает ошибки. Вот решение.
fetch(`http://endpoint.com`, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'omit', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
},
})
.then((res) => res.json())
.then((data)=> {
console.log('data', data)
})
Axios может не работать в некоторых ситуациях с Cors:
В цитате из этой темы:
Важно отметить, что режим, учетные данные и кроссдомен не поддерживаются для настройки Axios. Причина, по которой ваш пример работает при использовании fetch, заключается в том, что эти опции являются частью Request API (документация по режиму находится здесь).
Ошибки, которые вы могли видеть при выполнении запросов:
"Uncaught (in promise) SyntaxError: Unexpected end of input"
"Access to fetch at '...' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'"
"JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"