使用 fetch 而不是 jQuery 的 ajax 进行 GET API 调用
Using fetch instead of jQuery's ajax for a GET API call
我最近发现自己正在转换调用远程 API 的函数,从 return 调用回调到 return 调用 Promise
。我认为这也是将 $.ajax
调用替换为 fetch
调用的好机会,因为 fetch
已经 return 成为 Promise
。
但是,此特定调用是一个 GET
,它实际上需要有效负载(包含密钥和 return 类型)。具体来说,我称它为:
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: config.serviceUrl,
data: {
apiKey: key,
format: 'json'
}
})
.done(data => {...})
.fail((jqXHR, textStatus, errorThrown) => {...});
但是,fetch
没有 data
属性,如果您尝试发送带有 GET
的 body
,它会抛出错误请求(TypeError: Failed to execute 'fetch': Request with GET/HEAD method cannot have body
)。根据 Chromium forums,这是预期的行为。
请记住:我完全无法控制外部 API,因此提到使用 GET
发送有效负载违反了某些 API 协议,或者建议我更改底层打电话,没用。
在这种情况下可以使用fetch
吗?怎么样?
var headers = new Headers();
headers.append("Content-Type", "application/json; charset=utf-8");
fetch(config.serviceUrl + "?apiKey=" + key + "&format=json",
{headers:headers, method:"GET"}
).then(response => response.json())
.then(json => /* do stuff with `json` */)
.catch(err => console.error(err));
等同于当前 $.ajax()
调用。
jQuery 的 ajax
函数简单地 将 data
附加到 URL 作为 URL 参数 GET
请求:
data
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.
使用 fetch,您可以手动完成,也可以使用类似的方法:
var url = new URL("http://youapi.com")
var data = {
apiKey: key,
format: 'json'
}
Object.keys(data).forEach(key => url.searchParams.append(key, data[key]))
fetch(url)
我最近发现自己正在转换调用远程 API 的函数,从 return 调用回调到 return 调用 Promise
。我认为这也是将 $.ajax
调用替换为 fetch
调用的好机会,因为 fetch
已经 return 成为 Promise
。
但是,此特定调用是一个 GET
,它实际上需要有效负载(包含密钥和 return 类型)。具体来说,我称它为:
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: config.serviceUrl,
data: {
apiKey: key,
format: 'json'
}
})
.done(data => {...})
.fail((jqXHR, textStatus, errorThrown) => {...});
但是,fetch
没有 data
属性,如果您尝试发送带有 GET
的 body
,它会抛出错误请求(TypeError: Failed to execute 'fetch': Request with GET/HEAD method cannot have body
)。根据 Chromium forums,这是预期的行为。
请记住:我完全无法控制外部 API,因此提到使用 GET
发送有效负载违反了某些 API 协议,或者建议我更改底层打电话,没用。
在这种情况下可以使用fetch
吗?怎么样?
var headers = new Headers();
headers.append("Content-Type", "application/json; charset=utf-8");
fetch(config.serviceUrl + "?apiKey=" + key + "&format=json",
{headers:headers, method:"GET"}
).then(response => response.json())
.then(json => /* do stuff with `json` */)
.catch(err => console.error(err));
等同于当前 $.ajax()
调用。
jQuery 的 ajax
函数简单地 将 data
附加到 URL 作为 URL 参数 GET
请求:
data
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.
使用 fetch,您可以手动完成,也可以使用类似的方法:
var url = new URL("http://youapi.com")
var data = {
apiKey: key,
format: 'json'
}
Object.keys(data).forEach(key => url.searchParams.append(key, data[key]))
fetch(url)