fetch API 接受的第二个参数到底是什么?

What exactly is the second parameter that the fetch API takes?

我去了 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))
}

那么,request options 是一个 init 对象吗?

Init 对象是您可以用来初始化获取方法的选项。 以下是最常用的选项,您可以像在 init 对象中那样传递给 fetch

  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

上阅读更多相关内容

是的,就是“init”对象。不幸的是,这不是一个非常具有描述性的名称,但这就是 official specification calls it. You can see the properties it accepts at MDN or in the specification:

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
};

(如果你不熟悉的话,这个符号有点奇怪——左边的部分是值的类型,右边的部分是名称 属性)