PJCHENder 未整理筆記

[WebAPIs] Request 和 Response API

2018-08-21

[WebAPIs] Request 和 Response API

@(JavaScript)[JavaScript, webapis]

keywords: Request Object, Response Object

Request 和 Response API

Request Object

1
2
3
4
/**
* 建立 Request 物件
**/
const request = new Request('/images/sample1.jpg')

Response Object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 建立 Response 物件
**/
const imageBlob = new Blob([data], {type: 'image/jpeg'});
const imageResponse = new Response(imageBlob);

const stringResponse = new Response('Hello world');

// 透過 options 可以設定 Response 物件
const options = {
headers: {
'Content-Type': 'application/json'
}
}
const jsonResponse = new Response('{}', options);

操作 Response Object

1
2
3
4
5
6
7
8
/**
* 操作 Response Object
**/
const response = new Response('Hello world');
response.arrayBuffer().then((buffer) => {
console.log(new Uint8Array(buffer));
// Uint8Array(11) [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
});

其他操作 Response Object 的方法可以參考 Working with Response Object @ Google Developer - Web Fundamental

掃描二維條碼,分享此文章