request构造函数用于创建可复用的请求实例,需传入url和配置对象,其中method指定全大写http方法,默认"get";headers支持对象或headers实例;body适配post/put等方法并需匹配content-type;mode、credentials、cache、signal等控制跨域、凭据、缓存与中止。

用 Request 构造函数配置请求方法与参数,核心是传入 URL 和一个配置对象(init),其中 method 指定 HTTP 方法,其他字段如 headers、body、mode 等控制行为。它不直接发送请求,只是构造一个可复用的 Request 实例,后续传给 fetch() 即可。
指定请求方法(GET / POST / PUT / DELETE 等)
method 字段决定 HTTP 动词,默认为 "GET"。注意大小写敏感,必须全大写。
new Request("/api/users", { method: "GET" })new Request("/api/users", { method: "POST" })new Request("/api/users/123", { method: "PUT" })new Request("/api/users/123", { method: "DELETE" })
设置请求头(Headers)
headers 可以是对象、Headers 实例或字符串数组。推荐用对象或 Headers 实例,便于维护和类型安全。
- 用普通对象:
{ headers: { "Content-Type": "application/json" } } - 用
Headers实例(更灵活,支持重复键、大小写保留):const headers = new Headers(); headers.set("Authorization", "Bearer abc123");<br> new Request("/api/data", { headers })
注意:某些 header(如 Content-Length、Host)由浏览器自动设置,手动设置可能被忽略或报错。
携带请求体(body)与 Content-Type 匹配
body 仅对 POST、PUT、PATCH 等有载荷的方法有效。值可以是 String、FormData、Blob、URLSearchParams 或 ReadableStream。务必确保 Content-Type 头与实际数据格式一致。
- JSON 数据:
new Request("/api/login", {<br> method: "POST",<br> headers: { "Content-Type": "application/json" },<br> body: JSON.stringify({ username: "a", password: "b" })<br> }) - 表单数据:
const formData = new FormData(); formData.append("file", fileInput.files[0]);<br> new Request("/upload", { method: "POST", body: formData })
(此时不要手动设Content-Type,浏览器会自动生成带 boundary 的 multipart 头) - URL 编码参数:
new Request("/search", {<br> method: "POST",<br> headers: { "Content-Type": "application/x-www-form-urlencoded" },<br> body: new URLSearchParams({ q: "js", page: "1" })<br> })
常用附加配置(mode、credentials、cache 等)
这些选项影响请求的安全策略、凭据携带和缓存行为,常与跨域或登录态相关:
-
mode: "cors"(默认):允许跨域,但需服务端响应Access-Control-Allow-Origin -
mode: "no-cors":发出“隔离”请求(只允许简单方法 + 简单头),响应不可读,一般少用 -
credentials: "include":带上 Cookie 和 HTTP 认证信息(跨域时需服务端配合) -
cache: "no-cache"或"force-cache":控制是否走浏览器缓存 -
signal:传入AbortSignal实现请求中止(如用户取消操作)
例如带认证的跨域请求:
const controller = new AbortController();<br>
const req = new Request("https://api.example.com/data", {<br>
method: "GET",<br>
credentials: "include",<br>
signal: controller.signal<br>
});<br>
fetch(req).catch(err => { if (err.name === "AbortError") console.log("已取消"); });










