fetch基本使用(二)通过fetch的第二个参数定制HTTP请求

197 阅读1分钟

fetch基本使用(一)处理网络回应Response对象

上一篇讲了如何处理网络回应,这一篇讲一下设置请求的信息。 fetch的第二个参数可以设置请求参数的信息。

const response = fetch(url, {
  method: "GET",
  headers: {
    "Content-Type": "text/plain;charset=UTF-8"
  },
  body: undefined,
  referrer: "about:client",
  referrerPolicy: "no-referrer-when-downgrade",
  mode: "cors", 
  credentials: "same-origin",
  cache: "default",
  redirect: "follow",
  integrity: "",
  keepalive: false,
  signal: undefined
});
  • method 请求方法,入GET,POST
  • headers 请求头信息的设置。注意,有些标头不能通过headers属性设置,比如Content-LengthCookieHost等等。它们是由浏览器自动生成,无法修改。
  • body 任何你想加到请求body的数据,GET, DEAD没有body 我们先试下常用的请求:

发送JSON

async function api() {
  const data = { name: "gavin" };
  try {
    const res = await fetch("http://localhost:8888", {
      method: "POST",
      body: JSON.stringify(data),
    });
    const result = await res.json();
    console.log(result);
  } catch (error) {
    console.log(error, "err");
  }
}
  • cache 指定如何处理缓存
  • mode 指定请求的模式,cors, same-origin, no-cors.
  • credentials 指定属性是否发送cookie,可能的值 same-origin, include, omit. 跨域发送属性值设置为include.
  • keepalive 用于页面卸载时,告诉浏览器在后台保持连接,继续发送数据。
  • redirect 指定HTTP跳转的处理方法。 使用的话了解看看就可以,造轮子的话就的看官网和自己挨个试属性了。