main.ejs
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>서버 메인 화면</title>
</head>
<body>
<h1>
<%= count %>
</h1>
<button onclick="resetCount()">초기화</button>
<button onclick="countUp()">Up</button>
<script>
function resetCount() {
const requestOptions = {
method: "DELETE",
body: "",
redirect: "follow"
};
fetch("/count", requestOptions)
.then((response) => {
return response.json()
})
.then((json)=> {
if (json.result == 'OK') {
alert('삭제 성공했어요');
location.reload();
}
})
}
function countUp() {
const requestOptions = {
method: "PUT",
body: "",
redirect: "follow"
};
fetch("/count", requestOptions)
.then((response) => location.reload())
}
</script>
</body>
</html>
server.js
const express = require('express')
const app = express();
const port = 80;
let count = 0;
app.set('view engine', 'ejs');
app.listen(port, () => {
console.log('서버실행중: http://localhost:{port}');
});
app.get('/', (req, res) => {
// res.send('Hello World!' + count);
res.render('main', { count });
});
// count up api 만들기
app.put('/count', (req, res) => {
//count = count + 1
//count += 1
count ++
res.json({count});
})
app.delete('/count', (req, res)=> {
count = 0;
res.json({"result":"OK", count})
});