fetch方法请求接口数据

tech2022-12-09  48

可以 直接 拿过去使用哈 还是先来一段概念哈

Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。它还提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。

这种功能以前是使用 XMLHttpRequest 实现的。Fetch 提供了一个更理想的替代方案,可以很容易地被其他技术使用,例如 Service Workers。Fetch 还提供了专门的逻辑空间来定义其他与 HTTP 相关的概念,例如 CORS 和 HTTP 的扩展。

请注意,fetch 规范与 jQuery.ajax() 主要有三种方式的不同:

当接收到一个代表错误的 HTTP 状态码时,从 fetch() 返回的 Promise 不会被标记为 reject, 即使响应的 HTTP 状态码是 404 或 500。相反,它会将 Promise 状态标记为 resolve (但是会将 resolve 的返回值的 ok 属性设置为 false ),仅当网络故障时或请求被阻止时,才会标记为 reject。 fetch() 可以不会接受跨域 cookies;你也可以不能使用 fetch() 建立起跨域会话。其他网站的 Set-Cookie 头部字段将会被无视。 fetch 不会发送 cookies。除非你使用了credentials 的初始化选项。(自 2017 年 8 月 25 日以后,默认的 credentials 政策变更为 same-origin。Firefox 也在 61.0b13 版本中进行了修改)

/* @params url 请求地址 data 请求参数 type 请求类型 (默认是 post) @modifyTime 2021-01-12 @author yunchong_zhao */ function fetchData(url, data, type = "post") { // 默认按照 post请求哈 if (type == "get") { // 如果有参数的情况下 要拼接一下了 if (data) { url += "?"; for (var key in data) { url += `${key}=${data[key]}&`; } } url = url.replace(/&{1}$/, ''); // 去掉最后一个拼接的& return fetch(url).then(res => res.json()); } return fetch(url, { body: JSON.stringify(data), // must match 'Content-Type' header cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, same-origin, *omit headers: { 'content-type': 'application/json' }, method: type, // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, cors, *same-origin redirect: 'follow', // manual, *follow, error referrer: 'no-referrer', // *client, no-referrer }) .then(response => response.json()) // parses response to JSON }

请求 示例

// get 请求 postData("http://localhost:3000/",{name:"zhaoyunchong"}, 'get').then(res=>{ console.log(res); })
最新回复(0)