【问题标题】:What exactly is the second parameter that the fetch API takes?fetch API 采用的第二个参数究竟是什么?
【发布时间】:2020-01-27 14:28:55
【问题描述】:

我去了 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 对象吗?

【问题讨论】:

    标签: javascript fetch fetch-api


    【解决方案1】:

    Init object 是您可以用来初始化 fetch 方法的选项。 以下是您可以传递给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 上阅读更多信息

    【讨论】:

      【解决方案2】:

      是的,这就是“init”对象。不幸的是,这不是一个描述性很强的名称,但这就是official specification 所说的。您可以在at MDN 或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
      };
      

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

      【讨论】:

        猜你喜欢
        • 2014-08-23
        • 2015-01-05
        • 2012-05-10
        • 1970-01-01
        • 2017-04-25
        • 1970-01-01
        • 2014-06-18
        • 2011-08-27
        • 1970-01-01
        相关资源
        最近更新 更多