File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ <!DOCTYPE html>
2
+ < html >
3
+ < body >
4
+ < div id ="message "> </ div >
5
+ < script >
6
+
7
+ const message = document . getElementById ( 'message' ) ;
8
+
9
+ const fetch = url => new Promise ( ( resolve , reject ) => {
10
+ const xhr = new XMLHttpRequest ( ) ;
11
+ xhr . onreadystatechange = ( ) => {
12
+ if ( xhr . readyState === XMLHttpRequest . DONE ) {
13
+ if ( xhr . status === 200 ) resolve ( xhr . responseText ) ;
14
+ else reject ( `Status Code: ${ xhr . status } ` ) ;
15
+ }
16
+ } ;
17
+ xhr . open ( 'GET' , url , true ) ;
18
+ xhr . send ( ) ;
19
+ } ) ;
20
+
21
+ // Usage
22
+
23
+ fetch ( '/person' )
24
+ . then ( body => message . innerHTML = body )
25
+ . catch ( err => message . innerHTML = err ) ;
26
+
27
+ </ script >
28
+ </ body >
29
+ </ html >
Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+
3
+ const fs = require ( 'fs' ) ;
4
+ const http = require ( 'http' ) ;
5
+
6
+ const index = fs . readFileSync ( './4-fetch.html' ) ;
7
+ const person = { name : 'Marcus' } ;
8
+ const data = JSON . stringify ( person ) ;
9
+
10
+ http . createServer ( ( req , res ) => {
11
+ res . end ( req . url === '/person' ? data : index ) ;
12
+ } ) . listen ( 8000 ) ;
You can’t perform that action at this time.
0 commit comments