Что именно является вторым параметром, который принимает API выборки? - PullRequest
0 голосов
/ 27 января 2020

Я пошел в MDN и прочитал о fetch API и там написано:

You can also optionally pass in an init options object as the second argument

Предположим, у нас есть простая функция входа в систему:

const login = () => {
    const requestOptions = {
        method: "POST",
        headers: { "Content-type": "application/json" },
        body: JSON.stringify({ username, password })
    }

    return fetch(`apiUrl/users/authenticate`, requestOptions)
        .then(res = res.json)
            .then(data => console.log(data))
}

Итак, параметры запроса здесь init объект?

Ответы [ 2 ]

0 голосов
/ 27 января 2020

Да, это объект "init". К сожалению, это не очень описательное имя, но так его называет официальная спецификация 1003 *. Вы можете увидеть свойства, которые он принимает в MDN или в спецификации :

dictionary RequestInit {
  ByteString method;
  HeadersInit headers;
  BodyInit? body;
  USVString referrer;
  ReferrerPolicy referrerPolicy;
  RequestMode mode;
  RequestCredentials credentials;
  RequestCache cache;
  RequestRedirect redirect;
  DOMString integrity;
  boolean keepalive;
  AbortSignal? signal;
  any window; // can only be set to null
};

(запись немного странная, если вы с ней не знакомы - часть слева - это тип значения, а часть справа - имя свойства)

0 голосов
/ 27 января 2020

Init объект - это опции, с помощью которых вы можете инициализировать методы выборки. Ниже приведены наиболее часто используемые опции, которые вы можете передать fetch как в init объекте.

  1. method: 'POST', // *GET, POST, PUT, DELETE, etc.
  2. mode: 'cors', // no-cors, *cors, same-origin
  3. cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
  4. credentials: 'same-origin', // include, *same-origin, omit
  5. headers: {
    'Content-Type': 'application/json'
    // 'Content-Type': 'application/x-www-form-urlencoded',
  },
  7. redirect: 'follow', // manual, *follow, error
  8. referrerPolicy: 'no-referrer', // no-referrer, *client
  9. body: JSON.stringify(data) // body data type must match "Content-Type" header

Подробнее об этом вы можете узнать на MDN

...