请求正文
读取被拦截的请求主体。
你可以像通常读取任何 Fetch API Request
一样读取拦截的请求正文。响应解析器参数中获取的 request
对象实际上是一个常规的 Request
实例,可以照此操作。
¥You can read the intercepted request’s body as you normally would any Fetch API Request
. The request
object you get in the response resolver argument is literally a regular Request
instance and can be operated as such.
例如,你可以调用 await request.json()
以 JSON 格式读取请求主体:
¥For example, you can call await request.json()
to read the request’s body as JSON:
http.post<{ id: string }, Post>('/posts/:id', async ({ request }) => {
const newPost = await request.clone().json() // Post
})
强烈建议在读取拦截的请求正文之前先克隆该请求。如果你计划模拟响应,可以直接读取请求主体,但在直通/旁路场景下,不进行克隆就读取请求主体将导致异常(流无法读取两次)。
¥It’s highly recommended to clone the intercepted request before reading its body. While it’s okay to read the request body directly if you plan to mock its response, reading it without cloning in passthrough/bypass scenarios will result in an exception (streams cannot be read twice).
其他方法(如 .text()
、.formData()
、.blob()
等)也是如此。
¥The same is true for the other methods like .text()
, .formData()
, .blob()
, etc.