gpt4 book ai didi

javascript - JS - 使用 Fetch API 获取文本或 JSON

转载 作者:行者123 更新时间:2023-12-01 16:38:18 25 4
gpt4 key购买 nike

我正在从 jQuery AJAX 请求转移到新的 Fetch API(不反对 jQuery,我的网站上仍然有它,但 Fetch 看起来 - 根据 Jake ArchibaldDavid Walsh 以及恕我直言 - 成为新的发送异步请求的方式)。

因此,使用 jQuery,我有以下功能(或多或少):

function ajaxCall(type, url, data) {
return $.ajax({
type: type,
url: url,
data: data,
})
.fail(function(xhr, status, errorThrown) {
// Do fail stuff
})
.always(function(xhr, status) {
// Do always stuff
});
}

// Later...
var myAjax = ajaxCall(myType, myUrl, myData);
myAjax.done(function(xhr) {
// Do done stuff
});

通过这种方式,我可以调用一个函数来处理我可能需要的任何所有 ajax 请求(至少在大多数情况下...)。请注意,我没有声明 dataType,因为我使用 jQuery 的 intelligent guess .这样我的服务器可以向我发送任何响应并且我可以处理它(可能更聪明的方法是传递另一个具有数据类型的参数 - 在“智能猜测”出错的情况下,但这是我的方式设置)。

我现在正尝试使用新的 Fetch API 重新创建上述内容。目前我所拥有的是这样的:

function fetchCall(url, method, body) {
// This if statement is supposed to handle
// query selectors (which in GET requests go in the url)
// on GET requests - as opposed to POST req's which go in the body
if (method === 'GET') {
var data = body;
url = new URL(url, location.protocol + '//' + location.host + '/');
Object.keys(data).forEach(key => url.searchParams.append(key, data[key]));
body = undefined;
}
return fetch(url, {
method: method,
body: body
}).then(function(res) {
if (res.ok) return res;
throw new Error('Server error. Status code: ', res.status);
}).catch(function(err) {
console.log(err);
});
}

// Later...
var myFetch = fetchCall(myUrl, myMethod, myBody);
myFetch.then(function(res) {
console.log(res);
});

我遇到的问题是 if res.ok return res; 没有说明它是什么类型的响应(即 res.json()res.blob(), res.text() 等)。

Thus, I am wondering how to set up a dynamic way of setting the type of response body. Is this even possible at the Fetch API's current state of development? Is it just that there is something I am not duplicating in MDN?

在弄乱了这个之后,我还意识到我可以让它始终设置为 return res.text(); 如果调用应该是 JSON,请使用 JSON.parse(response);,但我确实希望它是动态的。如果我最终想要返回一个 blob() 怎么办?

最佳答案

因此,就对话所达到的范围而言,有一种方法可以了解已收到什么类型的内容,有两个备注:

  1. 通常,您必须始终知道并期望准确的内容类型,而在从某个远程端点获取数据的情况下,通用解决方案相当奇怪,并且
  2. Content-Type header 会告诉您收到的内容类型,但服务器可能会发送错误的 header ,这种情况很少见,因此可以忽略不计。

Response对象具有 header 属性(有点)Map , 所以你可以使用它的 get 方法来按键获取一个值。

检查返回值是否是您期望的特定 MIME 类型的最简单和最干净的方法是使用正则表达式:

// replace url with the actual API endpoint URL
fetch(url).then(response => {
const contentType = response.headers.get('Content-Type'); // -> "text/html; charset=utf-8"

if (/text\/html/i.test(contentType)) {
// do something when the Content-Type is text/html
} else if (/application\/json/.test(contentType)) {
// do something when the Content-Type is application/json
}
// and so on, for every Content-Type you need.
}).catch(error => {
// do something when error happens
});

关于javascript - JS - 使用 Fetch API 获取文本或 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39309411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com