File tree 3 files changed +65
-0
lines changed
Lecture14/express-ajax/express-ajax-todo
3 files changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ <!DOCTYPE html>
2
+ < html lang ="en ">
3
+ < head >
4
+ < meta charset ="UTF-8 ">
5
+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
6
+ < meta http-equiv ="X-UA-Compatible " content ="ie=edge ">
7
+ < title > Document</ title >
8
+ < script defer src ="./todo-frontend.js "> </ script >
9
+ </ head >
10
+ < body >
11
+ < h1 > Todo List</ h1 >
12
+
13
+ < input id ="newtask ">
14
+ < button id ="add "> ADD</ button >
15
+ < ul id ="tasklist "> </ ul >
16
+
17
+ </ body >
18
+ </ html >
Original file line number Diff line number Diff line change
1
+ let newtask = document . getElementById ( 'newtask' )
2
+ let add = document . getElementById ( 'add' )
3
+ let tasklist = document . getElementById ( 'tasklist' )
4
+
5
+ async function getTasks ( ) {
6
+ const resp = await fetch ( '/todos' )
7
+ const todos = await resp . json ( )
8
+ return todos
9
+ }
10
+
11
+ async function addTask ( taskName ) {
12
+ const resp = await fetch ( '/todos' , {
13
+ method : 'POST' ,
14
+ headers : {
15
+ 'Content-Type' : 'application/json' ,
16
+ } ,
17
+ body : JSON . stringify ( {
18
+ name : taskName ,
19
+ } ) ,
20
+ } )
21
+ const data = await resp . json ( )
22
+
23
+ if ( resp . status == 201 ) {
24
+ window . alert ( 'Todo ' + data . todoId + ' added' )
25
+ } else {
26
+ window . alert ( data . message )
27
+ }
28
+ }
29
+
30
+ async function renderList ( ) {
31
+ tasklist . innerHTML = ''
32
+ const todos = await getTasks ( )
33
+ for ( let t of todos ) {
34
+ let item = document . createElement ( 'li' )
35
+ item . innerText = t . name
36
+ tasklist . appendChild ( item )
37
+ }
38
+ }
39
+
40
+ add . onclick = async function ( ) {
41
+ await addTask ( newtask . value )
42
+ renderList ( )
43
+ }
44
+
45
+
46
+ renderList ( )
Original file line number Diff line number Diff line change @@ -6,6 +6,7 @@ app.use(express.urlencoded({extended: true}))
6
6
7
7
app . use ( '/todos' , require ( './routes/todos' ) )
8
8
9
+ app . use ( express . static ( __dirname + '/public' ) )
9
10
10
11
app . listen ( 8665 , ( ) => {
11
12
console . log ( 'http://localhost:8665' )
You can’t perform that action at this time.
0 commit comments