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

Javascript JS-使用Fetch API获取文本或JSON,javascript,fetch-api,Javascript,Fetch Api,我正在从jQueryAjax请求转向新的FetchAPI(与jQuery无关,我的站点中仍然有它,但Fetch看起来是发送异步请求的新方式,根据and和IMHO) 因此,使用jQuery,我有以下功能(或多或少): 这样,我就可以调用一个函数来处理我可能需要的任何和所有ajax请求(至少在大多数情况下…)。注意,我没有声明数据类型,因为我使用jQuery的。通过这种方式,我的服务器可以向我发送任何响应,我也可以处理它(可能更聪明的方法是用数据类型传递另一个参数——万一“智能猜测”出错,但这是我设

我正在从jQueryAjax请求转向新的FetchAPI(与jQuery无关,我的站点中仍然有它,但Fetch看起来是发送异步请求的新方式,根据and和IMHO)

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

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

我现在正试图用新的fetchapi重新创建上述内容。到目前为止,我所掌握的情况如下:

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返回res
没有说明它是什么类型的响应(即
res.json()
res.blob()
res.text()
,等等)

因此,我想知道如何建立一种动态的方式来设置响应主体的类型。在FetchAPI当前的开发状态下,这是否可能?是不是有些东西我没有重复


在处理完这个问题后,我还意识到我可以将它始终设置为
return res.text()JSON.parse(response),但我确实希望它是动态的。如果我最终想要返回一个
blob()

那么,就谈话内容而言,有一种方法可以理解收到了什么类型的内容,其中有两条注释:

  • 通常,您必须始终知道并期望确切的内容类型,如果从某个远程端点获取,则通用解决方案相当奇怪,并且
  • 内容类型
    标题将告诉您所接收内容的类型,但服务器可能会发送错误的标题,这种情况非常罕见,因此可以忽略不计
  • 该对象的
    header
    属性是(某种)a,因此可以使用其
    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
    });
    

    非常罕见的是,您不知道您得到的响应的
    内容类型。通常是这样的,并且给定请求的内容类型,典型的API端点的内容类型是一致的。使代码过于通用更可能是一种反模式。“这样做很重要吗?”RishatMuhametshin你提出了一个很好的观点。我确实想在我的Fetch“blackbox”(如果你可以这样称呼它的话)中实现这个函数。
    内容类型
    是我问题的答案吗?或者至少是其中的一部分?如果是这样,也许你可以在下面的回答中详细说明。是的,没错。让我以答案的形式写下来。
    // 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
    });