--- title: Request slug: Web/API/Request tags: - API - Fetch - Fetch API - Interface - NeedsTranslation - Networking - Reference - TopicStub - request translation_of: Web/API/Request ---
Интерфейс Request из Fetch API является запросом ресурсов или данных.
Создать новый объект Request можно, используя конструктор {{domxref("Request.Request","Request()")}}, однако чаще всего встречается способ возврата объекта Request , как результат операции API. Например такой как service worker {{domxref("FetchEvent.request")}}.
Request объект.default, reload, no-cache).audio, image, iframe, и т.д..)"omit", "same-origin", "include"). Значение по умолчанию: "same-origin".sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).GET, POST, и т.д.)cors, no-cors, same-origin, navigate.)follow, error, или manual.client).no-referrer).Request имплементирует {{domxref("Body")}}, таким образом наследуя следующие параметры:
Request объекта.Request имплементирует {{domxref("Body")}}, таким образом наследуя следующие параметры:
Note: The {{domxref("Body")}} functions can be run only once; subsequent calls will resolve with empty strings/ArrayBuffers.
In the following snippet, we create a new request using the Request() constructor (for an image file in the same directory as the script), then return some property values of the request:
const request = new Request('https://www.mozilla.org/favicon.ico');
const URL = request.url;
const method = request.method;
const credentials = request.credentials;
You could then fetch this request by passing the Request object in as a parameter to a {{domxref("WindowOrWorkerGlobalScope.fetch()")}} call, for example:
fetch(request)
.then(response => response.blob())
.then(blob => {
image.src = URL.createObjectURL(blob);
});
In the following snippet, we create a new request using the Request() constructor with some initial data and body content for an api request which need a body payload:
const 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;
Примечание: Типом тела может быть только {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}} или {{domxref("ReadableStream")}} поэтому, для добавления объекта JSON в полезную нагрузку вам необходимо структурировать этот объект.
Вы можете получить этот запрос API, передав объект Request в качестве параметра для вызова {{domxref("WindowOrWorkerGlobalScope.fetch()")}}, например, и получить ответ:
fetch(request)
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error('Что-то пошло не так на API сервере.');
}
})
.then(response => {
console.debug(response);
// ...
}).catch(error => {
console.error(error);
});
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('Fetch','#request-class','Request')}} | {{Spec2('Fetch')}} | Начальное определение |
{{Compat}}