Response - Web APIs 编辑

The Response interface of the Fetch API represents the response to a request.

You can create a new Response object using the Response.Response() constructor, but you are more likely to encounter a Response object being returned as the result of another API operation—for example, a service worker Fetchevent.respondWith, or a simple WindowOrWorkerGlobalScope.fetch().

Constructor

Response()
Creates a new Response object.

Properties

Response.headers Read only
The Headers object associated with the response.
Response.ok Read only
A boolean indicating whether the response was successful (status in the range 200299) or not.
Response.redirected Read only
Indicates whether or not the response is the result of a redirect (that is, its URL list has more than one entry).
Response.status Read only
The status code of the response. (This will be 200 for a success).
Response.statusText Read only
The status message corresponding to the status code. (e.g., OK for 200).
Response.trailers
A Promise resolving to a Headers object, associated with the response with Response.headers for values of the HTTP Trailer header.
Response.type Read only
The type of the response (e.g., basic, cors).
Response.url Read only
The URL of the response.
Response.useFinalURL
A boolean indicating whether this is the final URL of the response.

Body Interface Properties

Response implements Body, so it also has the following properties available to it:

Body.body Read only
A simple getter exposing a ReadableStream of the body contents.
Body.bodyUsed Read only
Stores a Boolean that declares whether the body has been used in a response yet.

Methods

Response.clone()
Creates a clone of a Response object.
Response.error()
Returns a new Response object associated with a network error.
Response.redirect()
Creates a new response with a different URL.

Body Interface Methods

Response implements Body, so it also has the following methods available to it:

Body.arrayBuffer()
Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer.
Body.blob()
Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob.
Body.formData()
Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object.
Body.json()
Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON, which is a JavaScript value of datatype object, string, etc.
Body.text()
Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text).

Examples

Fetching an image

In our basic fetch example (run example live) we use a simple fetch() call to grab an image and display it in an <img> element. The fetch() call returns a promise, which resolves to the Response object associated with the resource fetch operation.

You'll notice that since we are requesting an image, we need to run Body.blob (Response implements Body) to give the response its correct MIME type.

const image = document.querySelector('.my-image');
fetch('flowers.jpg').then(function(response) {
  return response.blob();
}).then(function(blob) {
  const objectURL = URL.createObjectURL(blob);
  image.src = objectURL;
});

You can also use the Response.Response() constructor to create your own custom Response object:

const response = new Response();

An Ajax Call

Here we call a PHP program file that generates a JSON string, displaying the result as a JSON value, including simple error handling.

// Function to do an Ajax call
const doAjax = async () => {
    const response = await fetch('Ajax.php'); // Generate the Response object
    if (response.ok) {
        const jVal = await response.json(); // Get JSON value from the response body
        return Promise.resolve(jVal);
        }
    else
        return Promise.reject('*** PHP file not found');
    }
}

// Call the function and output value or error message to console
doAjax().then(console.log).catch(console.log);

Specifications

SpecificationStatusComment
Fetch
The definition of 'Response' in that specification.
Living StandardInitial definition

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:82 次

字数:10458

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文