Fetch简单封装

一、什么是Fetch ?

1.Fetch本质上是一种标准,该标准定义了请求、响应和绑定的流程。
2.Fetch标准还定义了Fetch () JavaScript API。
3.可用于前后端,数据交互。
4.fetch返回的是promise对象,比XMLHttpRequest的实现更简洁,fetch 使用起来更简洁 ,完成工作所需的实际代码量也更少
5.fetch 可自定义是否携带Cookie。
6.fetch不像axios需要安装使用,fetch可以直接使用。

二、如何使用Fetch

Fetch API 提供了一种全局fetch()方法,该方法位于 WorkerOrGlobalScope 这一个 mixin 中 方法用于发起获取资源的请求。它返回一个 promise,这个 promise 会在请求响应后被 resolve,并传回 Response 对象。

fetch(input?: Request | string, init?: RequestInit): Promise<Response>

fetch(url, options).then(function(response) {
  // 处理 HTTP 响应
}, function(error) {
  // 处理网络错误
})

fetch() 参数

fetch方法可以接收两个参数input和options。

  • input 参数可以是字符串,包含要获取资源的 URL。也可以是一个 Request 对象。
  • options 是一个可选参数。一个配置项对象,包括所有对请求的设置。可选的参数有:

method: 请求使用的方法,如 GET、POST、DELETE、PUT等。
headers: 请求的头信息,包含与请求关联的Headers对象。
body: 请求的 body 信息。注意 GET 或 HEAD 方法的请求不能包含 body 信息
mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
credentials: 请求的 credentials,如 omit、same-origin 或者 include。为了在当前域名内自动发送 cookie , 必须提供这个选项。

三、常用的fetch请求

html

fetch('/index/fetchHtml')
  .then(res => {
    return res.text() // 定义返回格式。
  }).then(res => {
    document.body.innerHTML += res
  })
  .catch((err) => {
  })

JSON

fetch('请求路径')
  .then((res) => {
    return res.json()
  })
  .then(res => {
    console.log(res)
  })
  .catch((err => {
  }))

POST JSON

fetch('请求路径',{
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: '张麻子',
    age: '26',
  })
})
  .then((res) => {
    return res.json()
  })
  .then(res => {
    console.log(res)
  })
  .catch((err => {
  }))

4、fetch注意事项

1. 错误处理

fetch只有在网络错误的情况,返回的promise会被reject。成功的 fetch() 检查不仅要包括 promise 被 resolve,还要包括 Response.ok 属性为 true。HTTP 404 状态并不被认为是网络错误,所以Promise的状态为resolve。

2. credentials 设置

fetch可以通过credentials自己控制发送请求时是否带上cookie。credentials可设置为include、same-origin、omit。include为了让浏览器发送包含凭据的请求(即使是跨域源)。如果你只想在请求URL与调用脚本位于同一起源处时发送凭据,请添加credentials: 'same-origin'。要改为确保浏览器不在请求中包含凭据,请使用credentials: 'omit'。

5.fetch简单封装

1.和src同级新建一个api(名字可以随意起)的文件夹,在文件夹里面新建一个request.js (名字可以随意起)文件内容如下:

export default async(url = '', data = {}, type = 'GET') => {
    const baseUrl = "https://api.it120.cc/small4" // 基础路径
    type = type.toUpperCase(); // 请求方式小写转换成大写
    url = baseUrl + url; // 请求地址的拼接

    if (type == 'GET') {
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }
    let requestConfig = {
        credentials: 'same-origin',
        method: type,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        mode: "cors", // 用来决定是否允许跨域请求  值有 三个 same-origin,no-cors(默认)以及 cores;
        cache: "force-cache" // 是否缓存请求资源 可选值有 default 、 no-store 、 reload 、 no-cache 、 force-cache 或者 only-if-cached 。
    }

    if (type == 'POST') {
        Object.defineProperty(requestConfig, 'body', {
            value: JSON.stringify(data)
        })
    }
    try {
        const response = await fetch(url, requestConfig);
        const responseJson = await response.json();
        return responseJson
    } catch (error) {
        throw new Error(error)
    }
}

6.封装接口

import api from '../request.js';

下面是简写的形式
// getXXX 自定义的接口名字
export const getXXX = (params) => api(`/apigb/v1/component`, params)

export const postXXX = (params) => api.post(`/apigb/v1/component/update-info`, params,'post')



 

猜你喜欢

转载自blog.csdn.net/m0_45865109/article/details/125554425
今日推荐