示例
在下面的代码片段中,我们使用 Request() 构造函数创建一个新请求(用于与脚本在同一目录下的图像文件),然后返回请求的一些属性值。
jsconst request = new Request("https://www.mozilla.org/favicon.ico");
const url = request.url;
const method = request.method;
const credentials = request.credentials;
然后,您可以通过将 Request 对象作为参数传递给 fetch() 调用来获取此请求,例如:
jsfetch(request)
.then((response) => response.blob())
.then((blob) => {
image.src = URL.createObjectURL(blob);
});
在下面的代码片段中,我们使用 Request() 构造函数创建了一个带有初始数据和请求正文内容的新请求,用于需要请求正文负载的 API 请求。
jsconst request = new Request("https://example.com", {
method: "POST",
body: '{"foo": "bar"}',
});
const url = request.url;
const method = request.method;
const credentials = request.credentials;
const bodyUsed = request.bodyUsed;
注意: 请求正文只能是 Blob、ArrayBuffer、TypedArray、DataView、FormData、URLSearchParams、ReadableStream 或 String 对象,以及字符串字面量;因此,要将 JSON 对象添加到负载中,您需要对该对象进行字符串化。
然后,您可以将此 API 请求作为参数传递给 fetch() 调用来获取此 API 请求,例如,并获取响应:
jsfetch(request)
.then((response) => {
if (response.status !== 200) {
throw new Error("Something went wrong on API server!");
}
return response.json();
})
.then((response) => {
console.debug(response);
// …
})
.catch((error) => {
console.error(error);
});