重点:使用 fetch() 函数发起 ajax 请求

简介

fetch() 方法是一个 window的全局方法,用于发起获取资源的请求。它返回一个 promise,这个 promise 会在请求响应后被 resolve,并传回 Response 对象。

参数

传入两个参数:

1.请求地址或一个Request对象

2.一个配置项对象,包括所有对请求的设置。

可选的参数有:

  • method: 请求使用的方法,如 GET、POST。
  • headers: 请求的头信息
  • body: 请求体信息,可以是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象。
  • mode: 请求的模式,如 cors、no-cors 或者 same-origin。
  • credentials: 请求的 credentials,如 omit、same-origin 或者 include。
  • cache: 请求的 cache 模式:default、 no-store、 reload 、 no-cache、 force-cache 或者 only-if-cached。
  • redirect: 可用的 redirect 模式:follow (自动重定向), error (如果产生重定向将自动终止并且抛出一个错误),或者 manual (手动处理重定向)。在 Chrome 中默认使用 follow(Chrome 47 之前的默认值是 manual)。
  • referrer: 一个 USVString 可以是 no-referrer、client 或一个 URL。默认是 client。
  • referrerPolicy: 指定了 HTTP 头部 referer 字段的值。可能为以下值之一:no-referrer、 no-referrer-when-downgrade、origin、origin-when-cross-origin、 unsafe-url。
  • integrity: 包括请求的 subresource integrity 值(例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。

案例:

fetch("http://localhost:3000/users", {
  //请求方法
  method: "POST",
  //请求头
  headers: { name: "zs" },
  // 请求体
  body: "username=zs&password=123",
})
  .then((res) => {
    // Response 对象
    console.log(res);
    //return res.text();
    return res.json(); //返回一个 promise,将响应数据转为对象形式传入resolve,再次 .then 即可获得
  })
  .then((data) => {
    //响应数据
    console.log(data);
  });

结果:

 

posted @ 2022-09-27 15:42  Lamb~  阅读(120)  评论(0编辑  收藏  举报