--- title: Request slug: Web/API/Request translation_of: Web/API/Request ---
Request接口?用来表示资源请求。你可以使用 {{domxref("Request.Request()")}} ?构造函数创建一个Request 对象,但是你可能会遇到一个 Request 对象作为其它 API 的操作被返回,比如一个 service worker的{{domxref("FetchEvent.request")}}。
Request 对象。GET, POST, 等.)audio, image, iframe, 等)client)。no-referrer)。cors, no-cors, same-origin, navigate).omit, same-origin). follow ,error或者manual。sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).default, reload, no-cache).Request实现了{{domxref("Body")}}, 所以它还具有以下属性可用:
Request实现 {{domxref("Body")}}, 因此它也有以下方法可用:
注意:这些Body功能只能运行一次; 随后的调用将通过空strings/ ArrayBuffers解析.
在下面的代码中,我们使用 Request ( ) 构造函数创建了一个新的 request实例 (用来请求同一目录下的图片), 然后返回请求的一些属性。
const myRequest = new Request('http://localhost/flowers.jpg');
const myURL = myRequest.url; // http://localhost/flowers.jpg
const myMethod = myRequest.method; // GET
const myCred = myRequest.credentials; // omit
然后,通过将Request对象作为参数传递给{{domxref("GlobalFetch.fetch()")}}调用来获取此请求,例如:
fetch(myRequest)
.then(response => response.blob())
.then(blob => {
myImage.src = URL.createObjectURL(blob);
});
在下面的代码片段中,我们使用Request()构造函数创建了一个新的request,其中包含一些初始数据和正文内容,用于需要主体有效载荷的api请求:
const myRequest = new Request('http://localhost/api', {method: 'POST', body: '{"foo":"bar"}'});
const myURL = myRequest.url; // http://localhost/api
const myMethod = myRequest.method; // POST
const myCred = myRequest.credentials; // omit
const bodyUsed = myRequest.bodyUsed;
注意:body类型只能是一个{{domxref("Blob")}},{{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}} 或者{{domxref("ReadableStream")}}类型,因此增加一个JSON对象的有效载荷则需要字符串化该对象.
例如,您可以通过将Request对象作为参数传递给{{domxref("GlobalFetch.fetch()")}}调用来获取此api请求,并获得响应:
fetch(myRequest)
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error('Something went wrong on api server!');
}
})
.then(response => {
console.debug(response);
// ...
}).catch(error => {
console.error(error);
});
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('Fetch','#request-class','Request')}} | {{Spec2('Fetch')}} | Initial definition |
{{Compat("api.Request")}}