mediol-name
@mediol-name
Wordpress Developer

Почему не могу получить объект с товарами по API?

Пытаюсь получить товары по АПИ, прошел авторизацию, а дальше 3 ошибки:
1) Access to fetch at 'сайт' from origin 'сайт' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
2) Failed to load resource:
3) Uncaught (in promise) TypeError: Failed to fetch at

Выполняю запрос от домена, который указан в аккаунте. На него давали АПИ токен.

Вот мой код:
const username = 'username';
const clientSecret = 'token';

// Пример отправки POST запроса:
async function getAccess(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *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: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *client
    body: `username=${data.username}&client_secret=${data.client_secret}` // body data type must match "Content-Type" header
  });

  return await response.json(); // parses JSON response into native JavaScript objects
}

let access_token = '';
let token_type = '';

getAccess('https://api.nsonline.com.ua/api/access_token/', { username: username, client_secret: clientSecret  })
  .then((data) => {
    access_token = data.access_token;
    token_type = data.token_type;
    console.log(access_token);
  })
  .then(() => {
    fetch('https://api.nsonline.com.ua/api/catalog/product/', {
      mode: 'cors', // no-cors, *cors, same-origin
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `${token_type} ${access_token}`,
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      redirect: 'follow', // manual, *follow, error
      referrerPolicy: 'no-referrer', // no-referrer, *client
    })
    .then((response) => console.log(response));
  })

Что не так?
  • Вопрос задан
  • 77 просмотров
Пригласить эксперта
Ответы на вопрос 1
Rsa97
@Rsa97
Для правильного вопроса надо знать половину ответа
Во-первых, CORS.
Во-вторых Preflight.
Видимо, на API не реализован ответ на запрос OPTIONS в Preflight-запросе.
Если API не ваше, то лучше делать запрос через свой бэкенд. Браузер посылает запрос на ваш бэк, ваш бэк запрашивает API и возвращает ответ браузеру.
Ну либо обращайтесь в техподдержку владельца API.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы