Request
Experimental: 这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。
Request
接口?用来表示资源请求。你可以使用 Request.Request()
?构造函数创建一个Request 对象,但是你可能会遇到一个 Request 对象作为其它 API 的操作被返回,比如一个
service worker的FetchEvent.request
(en-US)。
构造器
Request.Request()
- 创建一个新的
Request
对象。
属性
Request.method
只读- 包含请求的方法 (
GET
,POST
, 等.) Request.url
只读- 包含这个请求的URL。
Request.headers
只读- 包含请求相关的
Headers
对象。 Request.context
(en-US) 只读 Deprecated- 包含请求的上下文(例如:
audio
,image
,iframe
, 等) Request.referrer
(en-US) 只读- ?包含请求的来源 (例如:
client
)。 Request.referrerPolicy
(en-US) 只读- ?包含请求来源的策略 (例如:
no-referrer
)。 Request.mode
只读- 包含请求的模式 (例如:
cors
,no-cors
,same-origin
,navigate
). Request.credentials
只读- 包含请求的证书(例如:
omit
,same-origin
). Request.redirect
(en-US) 只读- 包含?如何处理重定向模式,它可能是一个
follow
,error
或者manual
。 Request.integrity
(en-US) 只读- 包含请求的子资源的完整性值 (例如:
sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=
). Request.cache
只读- 包含请求的缓存模式 (例如:
default
,reload
,no-cache
).
Request
实现了Body
, 所以它还具有以下属性可用:
Body.body
(en-US) 只读- 一个简单getter用于曝光一个
ReadableStream
的主体内容.
Body.bodyUsed
(en-US) 只读- 存储一个
Boolean
(en-US)判断主体是否已经被用于一个响应中.
方法
Request.clone()
- 创建当前request的副本。
Request
实现 Body
, 因此它也有以下方法可用:
Body.arrayBuffer()
(en-US)- 返回解决一个
ArrayBuffer
表示的请求主体的promise. Body.blob()
(en-US)- 返回解决一个
Blob
表示的请求主体的promise. Body.formData()
(en-US)- 返回解决一个
FormData
表示的请求主体的promise. Body.json()
(en-US)- 返回解决一个
JSON
表示的请求主体的promise. Body.text()
(en-US)- 返回解决一个
USVString
(文本)表示的请求主体的promise.
注意:这些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对象作为参数传递给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类型只能是一个Blob
,BufferSource
(en-US), FormData
, URLSearchParams
, USVString
或者ReadableStream
类型,因此增加一个JSON对象的有效载荷则需要字符串化该对象.
例如,您可以通过将Request
对象作为参数传递给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 |
---|---|---|
Fetch Request |
Living Standard | Initial definition |
浏览器兼容性
BCD tables only load in the browser