Skip to content

Commit 591dad9

Browse files
express ajax todo
Signed-off-by: Arnav Gupta <[email protected]>
1 parent 3b279c8 commit 591dad9

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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 numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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()

Lecture14/express-ajax/express-ajax-todo/server.js

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ app.use(express.urlencoded({extended: true}))
66

77
app.use('/todos', require('./routes/todos'))
88

9+
app.use(express.static(__dirname + '/public'))
910

1011
app.listen(8665, () => {
1112
console.log('http://localhost:8665')

0 commit comments

Comments
 (0)