File tree Expand file tree Collapse file tree 2 files changed +91
-0
lines changed
Expand file tree Collapse file tree 2 files changed +91
-0
lines changed Original file line number Diff line number Diff line change 1+ // ts-node example/fetch-example-server.ts
2+ // open example/fetch-example.html
3+
4+ import http from "http" ;
5+ import { encode } from "../src" ;
6+
7+ const hostname = "127.0.0.1" ;
8+ const port = 8080 ;
9+
10+ function bufferView ( b : Uint8Array ) {
11+ return Buffer . from ( b . buffer , b . byteOffset , b . byteLength ) ;
12+ }
13+
14+ const server = http . createServer ( ( req , res ) => {
15+ console . log ( "accept:" , req . method , req . url ) ;
16+
17+ res . statusCode = 200 ;
18+ res . setHeader ( "content-type" , "application/x-msgpack" ) ;
19+ res . setHeader ( "access-control-allow-origin" , "*" ) ;
20+ res . end (
21+ bufferView (
22+ encode ( {
23+ message : "Hello, world!" ,
24+ } ) ,
25+ ) ,
26+ ) ;
27+ } ) ;
28+
29+ server . listen ( port , hostname , ( ) => {
30+ console . log ( `Server running at http://${ hostname } :${ port } /` ) ;
31+ } ) ;
Original file line number Diff line number Diff line change 1+ <!DOCTYPE html>
2+ < html lang ="en ">
3+
4+ < head >
5+ < meta charset ="UTF-8 ">
6+ < script src ="../dist.es5/msgpack.min.js "> </ script >
7+ < style >
8+ main {
9+ width : 80% ;
10+ margin : 20px auto;
11+ }
12+ </ style >
13+ </ head >
14+
15+ < body >
16+ < main >
17+ < h1 > Fetch API example</ h1 >
18+ < p > Open DevTool and see the console logs.</ p >
19+ < script id ="script ">
20+ const MSGPACK_TYPE = "application/x-msgpack" ;
21+
22+ const url = "http://127.0.0.1:8080/" ;
23+
24+ ( async ( ) => {
25+ // decode()
26+ {
27+ const response = await fetch ( url ) ;
28+ const contentType = response . headers . get ( "content-type" ) ;
29+ if ( contentType && contentType . startsWith ( MSGPACK_TYPE ) && response . body != null ) {
30+ const object = await MessagePack . decodeAsync ( response . body ) ;
31+ console . log ( "decode:" , object ) ;
32+ } else {
33+ console . error ( "Something is wrong!" ) ;
34+ }
35+
36+ }
37+
38+ // decodeAsync()
39+ {
40+ const response = await fetch ( url ) ;
41+ const contentType = response . headers . get ( "content-type" ) ;
42+ if ( contentType && contentType . startsWith ( MSGPACK_TYPE ) && response . body != null ) {
43+ const object = MessagePack . decode ( await response . arrayBuffer ( ) ) ;
44+ console . log ( "decodeAsync:" , object ) ;
45+ } else {
46+ console . error ( "Something is wrong!" ) ;
47+ }
48+ }
49+ } ) ( )
50+ </ script >
51+ < script >
52+ const script = document . getElementById ( "script" ) ;
53+ document . write ( "<pre><code>" ) ;
54+ document . write ( script . innerText . replace ( / ^ { 6 } / gms, "" ) ) ;
55+ document . write ( "</code><pre>" ) ;
56+ </ script >
57+ </ main >
58+ </ body >
59+
60+ </ html >
You can’t perform that action at this time.
0 commit comments