HTTP 请求
Request 接口是 Fetch API 的一部分,表示 fetch() 的请求。
构造函数 Jump to heading
Request() 构造函数创建一个新的 Request 实例。
let request = new Request(resource, init);
参数 Jump to heading
名称 | 类型 | 可选 | 描述 |
---|---|---|---|
resource | Request 或 USVString |
false |
资源可以是一个请求对象或一个 URL 字符串。 |
init | RequestInit |
true |
init 对象允许你设置应用于请求的可选参数。 |
返回类型是一个 Request
实例。
RequestInit
Jump to heading
名称 | 类型 | 默认值 | 描述 |
---|---|---|---|
method |
string |
GET |
请求的方法。 |
headers |
Headers 或 { [key: string]: string } |
无 | 请求的 Headers。 |
body |
Blob , BufferSource , FormData , URLSearchParams , USVString , 或 ReadableStream |
无 | 请求的 body。 |
cache |
string |
无 | 请求的缓存模式。 |
credentials |
string |
same-origin |
请求的凭证模式。 |
integrity |
string |
无 | 请求 body 的加密哈希值。 |
mode |
string |
cors |
你想要使用的请求模式。 |
redirect |
string |
follow |
重定向的处理模式。 |
referrer |
string |
about:client |
指定 no-referrer , client 或 URL 的 USVString 。 |
属性 Jump to heading
名称 | 类型 | 描述 |
---|---|---|
cache |
string |
缓存模式指示浏览器应如何缓存请求 (default , no-cache , 等)。 |
credentials |
string |
凭证 (omit , same-origin , 等) 指示用户代理是否应在 CORs 请求的情况下发送 cookies。 |
destination |
RequestDestination |
字符串指示请求的内容类型。 |
body |
ReadableStream |
getter 暴露 body 内容的 ReadableStream 。 |
bodyUsed |
boolean |
指示 body 内容是否已读取。 |
url |
USVString |
请求的 URL。 |
headers |
Headers |
与请求关联的 headers。 |
integrity |
string |
请求 body 的加密哈希值。 |
method |
string |
请求的方法 (POST , GET , 等)。 |
mode |
string |
指示请求的模式 (例如 cors )。 |
redirect |
string |
重定向的处理模式。 |
referrer |
string |
请求的 referrer。 |
referrerPolicy |
string |
请求的 referrer 策略 |
以上所有属性均为只读。
方法 Jump to heading
名称 | 描述 |
---|---|
arrayBuffer() |
读取 body 流至完成并返回一个 ArrayBuffer 对象。 |
blob() |
读取 body 流至完成并返回一个 Blob 对象。 |
formData() |
读取 body 流至完成并返回一个 FormData 对象。 |
json() |
读取 body 流至完成,将其解析为 JSON 并返回一个 JavaScript 对象。 |
text() |
读取 body 流至完成并返回一个 USVString 对象 (文本)。 |
clone() |
克隆 Request 对象。 |
示例 Jump to heading
function handler(_req) {
// 创建一个 post 请求
const request = new Request("https://post.deno.dev", {
method: "POST",
body: JSON.stringify({
message: "Hello world!",
}),
headers: {
"content-type": "application/json",
},
});
console.log(request.method); // POST
console.log(request.headers.get("content-type")); // application/json
return fetch(request);
}
Deno.serve(handler);