관리 메뉴

거니의 velog

231117_Node.js 개론 3 본문

대덕인재개발원/대덕인재개발원_파이썬 프로그래밍

231117_Node.js 개론 3

Unlimited00 2023. 11. 17. 08:33

[my_express.js]

const express = require('express');
const app = express();
const port = 3000;

const bodyParser = require('body-parser');
app.use(bodyParser.json());	// json 등록
app.use(bodyParser.urlencoded({ extended : false })); // URL-encoded 등록

app.set('view engine', 'ejs');
app.set('views', './views');

const DaoEmp = require('./daoemp.js');
const de = new DaoEmp();

app.get('/', (req, res) => {
	res.send('HELLO EXPRESS');
});

app.listen(port, () => {
	console.log(`Example app listening on port ${port}`);
});

- http://localhost:3000/


https://expressjs.com/en/starter/static-files.html

 

Serving static files in Express

Serving static files in Express To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The function signature is: express.static(root, [options]) The root argument specifies th

expressjs.com

https://balmostory.tistory.com/159

 

node js ajax post 예제

ajax는 페이지의 일부만 로드하는 기술입니다. 오늘은 nodejs ajax를 사용하는 방법에 대해 알아보도록 하겠습니다. 1. html 코드 작성 아래와 같이 html 코드를 작성해 주세요. ajaxbutton 2. 서버 코드 cons

balmostory.tistory.com

[my_express.js]

const express = require('express');
const app = express();
const port = 3000;

const bodyParser = require('body-parser');
app.use(bodyParser.json());	// json 등록
app.use(bodyParser.urlencoded({ extended : false })); // URL-encoded 등록

app.set('view engine', 'ejs');
app.set('views', './views');

app.use('/static', express.static('static'));

const DaoEmp = require('./daoemp.js');
const de = new DaoEmp();

app.get('/', (req, res) => {
	res.send("Hello Express!");
});

// /jquery.ajax => {'msg' : 'ok'}
app.post('/jquery.ajax', (req, res) => {
	const e_id = req.body.e_id;
	console.log("e_id : " + e_id);
	var myjson = {'msg' : 'ok'};
	res.json(myjson);
});

app.listen(port, () => {
	console.log(`Example app listening on port ${port}`);
});

[ajax.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS01</title>
		<script src="jquery-3.7.1.js"></script>
		<script>
			$(function(){
				$("#btn").bind("click", function(){
					var data = {
						"e_id" : 1
					};
				    $.ajax({
				        type : 'POST',
				        url : '/jquery.ajax',
				        data : data,
				        success : function(res){
				            console.log(res);
				        }
				   });
				});
			});
		</script>
	</head>
	<body>
		JS01
		<div id="mydiv">Good Morning</div>
		<button type="button" id="btn">click</button>
	</body>
</html>

- http://localhost:3000/static/ajax.html


[package.json]

{
  "dependencies": {
    "axios": "^1.6.2",
    "body-parser": "^1.20.2",
    "ejs": "^3.1.9",
    "express": "^4.18.2",
    "mysql": "^2.18.1",
    "pug": "^3.0.2",
    "sync-mysql": "^3.0.1"
  }
}

https://inpa.tistory.com/entry/AXIOS-%F0%9F%93%9A-%EC%84%A4%EC%B9%98-%EC%82%AC%EC%9A%A9

 

📚 AXIOS 설치 & 특징 & 문법 💯 정리

Axios 라이브러리 Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리 아다. 쉽게 말해서 백엔드랑 프론트엔드랑 통신을 쉽게하기 위해 Ajax와 더불어 사용한다. 이미

inpa.tistory.com

[my_axios.js]

const express = require('express');
const app = express();
const port = 3000;

const bodyParser = require('body-parser');
app.use(bodyParser.json());	// json 등록
app.use(bodyParser.urlencoded({ extended : false })); // URL-encoded 등록

app.set('view engine', 'ejs');
app.set('views', './views');

app.use('/static', express.static('static'));

const DaoEmp = require('./daoemp.js');
const de = new DaoEmp();

app.get('/', (req, res) => {
	res.send("Hello Express!");
});

app.post('/axois.ajax', (req, res) => {
	const e_id = req.body.e_id;
	console.log("e_id : " + e_id);
	var myjson = {'msg' : 'ok2'};
	res.json(myjson);
});

app.listen(port, () => {
	console.log(`Example app listening on port ${port}`);
});

[axios.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS01</title>
		<script src="jquery-3.7.1.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
		<script>
			function fn_axios(){
				axios.post('/axois.ajax', {
				   	e_id : 1
				})
				.then(function (res) {
				    console.log(res);
				});  
			}
			$(function(){
				$("#btn").on("click", function(){
					fn_axios();
				});
			});
		</script>
	</head>
	<body>
		JS01
		<div id="mydiv">Good Morning</div>
		<button type="button" id="btn">click</button>
	</body>
</html>

- http://localhost:3000/static/axios.html


https://velog.io/@seoltang/fetch-POST-Request

 

fetch 함수: POST Request

POST 요청, fetch 함수, then() 메서드에서의 분기 처리, Response message 처리

velog.io

const express = require('express');
const app = express();
const port = 3000;

const bodyParser = require('body-parser');
app.use(bodyParser.json());	// json 등록
app.use(bodyParser.urlencoded({ extended : false })); // URL-encoded 등록

app.set('view engine', 'ejs');
app.set('views', './views');

app.use('/static', express.static('static'));

const DaoEmp = require('./daoemp.js');
const de = new DaoEmp();

app.get('/', (req, res) => {
	res.send("Hello Express!");
});

app.post('/axois.ajax', (req, res) => {
	var e_id = req.body.e_id;
	console.log("e_id : " + e_id);
	var myjson = {'msg' : 'ok2'};
	res.json(myjson);
});

app.post('/fetch.ajax', (req, res) => {
	var e_id = req.body.e_id;
	console.log("e_id : " + e_id);
	var myjson = {'msg' : 'ok3'};
	res.json(myjson);
});

app.listen(port, () => {
	console.log(`Example app listening on port ${port}`);
});
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS01</title>
		<script src="jquery-3.7.1.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/3.6.19/fetch.min.js" integrity="sha512-XVBqknFNWcPmY+09EHhvhcZChBukN5ofG0hSD6HxrlaRJvPpKArrzs7EE64Tu3d15Ills2RS7qluokksKDyu/Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
		<script>
			function fn_axios(){
				axios.post('/axois.ajax', {
					e_id : 1
				})
				.then((res) => 
				    console.log(res)
				);  
			}
			function fn_fetch(){
				fetch("/fetch.ajax", {
					method: "POST",
					headers: {
						"Content-Type" : "application/json",
					},
					body: JSON.stringify({
						e_id : 2
					}),
				})
				.then((res) => 
					//console.log(res)
					res.json()
				)
				.then((result) => 
					console.log(result)
				);
			}
			$(function(){
				$("#btn").on("click", function(){
					fn_axios();
					fn_fetch();
				});
			});
		</script>
	</head>
	<body>
		JS01
		<div id="mydiv">Good Morning</div>
		<button type="button" id="btn">click</button>
	</body>
</html>

- http://localhost:3000/static/axios.html


[my_axios.js]

const express = require('express');
const app = express();
const port = 3000;

const bodyParser = require('body-parser');
app.use(bodyParser.json());	// json 등록
app.use(bodyParser.urlencoded({ extended : false })); // URL-encoded 등록

app.set('view engine', 'ejs');
app.set('views', './views');

app.use('/static', express.static('static'));

const DaoEmp = require('./daoemp.js');
const de = new DaoEmp();

app.get('/', (req, res) => {
	res.redirect("/static/emp.html");
});

app.post('/axois.ajax', (req, res) => {
	var e_id = req.body.e_id;
	console.log("e_id : " + e_id);
	var myjson = {'msg' : 'ok2'};
	res.json(myjson);
});

app.post('/selectlist.ajax', (req, res) => {
	var list = de.selectList();
	var data = {
		'list' : list
	};
	res.json(data);
});

app.listen(port, () => {
	console.log(`Example app listening on port ${port}`);
});

[emp.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS01</title>
		<script src="jquery-3.7.1.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/3.6.19/fetch.min.js" integrity="sha512-XVBqknFNWcPmY+09EHhvhcZChBukN5ofG0hSD6HxrlaRJvPpKArrzs7EE64Tu3d15Ills2RS7qluokksKDyu/Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
		<script>
			function setList(list){
	            var txt = "";
	            for(var i=0; i < list.length; i++) {
	            	var vo = list[i];
	            	var e_id = vo.e_id;
	            	var e_name = vo.e_name;
	            	var gen = vo.gen;
	            	var addr = vo.addr;
	            	txt += `
	            		<tr>
							<th><a href='javascript:fn_select("${e_id}")'>${e_id}</a></th>
							<th>${e_name}</th>
							<th>${gen}</th>
							<th>${addr}</th>
						</tr>
	            	`;
	            }
	            $("#mytbody").html(txt);
			}
		
			function fn_selectlist(){
				axios.post('/selectlist.ajax', {
					e_id : 1
				})
				.then(function(res) {
				    console.log(res.data.list);
					var list = res.data.list;
					setList(list);
				})
			}
			
			$(function(){
				fn_selectlist();
			});
		</script>
	</head>
	<body>
		EMP_HTML
		<table border="1">
			<colgroup>
				<col width="25%" />
				<col width="25%" />
				<col width="25%" />
				<col width="25%" />
			</colgroup>
			<thead>
				<tr>
					<th>사원번호</th>
					<th>이름</th>
					<th>성별</th>
					<th>주소</th>
				</tr>
			</thead>
			<tbody id="mytbody">
				<tr>
					<td colspan="4">검색된 데이터가 없습니다</td>
				</tr>
			</tbody>
		</table>
		<br />
		<hr />
		<br />
		<table border="1">
			<colgroup>
				<col width="30%" />
				<col width="70%" />
			</colgroup>
			<tr>
				<td>사번</td>
				<td>
					<input type="text" id="e_id" name="e_id" />
				</td>
			</tr>
			<tr>
				<td>이름</td>
				<td>
					<input type="text" id="e_name" name="e_name" />
				</td>
			</tr>
			<tr>
				<td>성별</td>
				<td>
					<input type="text" id="gen" name="gen" />
				</td>
			</tr>
			<tr>
				<td>주소</td>
				<td>
					<input type="text" id="addr" name="addr" />
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<button type="button" onclick="fn_add()">추가</button>
					<button type="button" onclick="fn_mod()">수정</button>
					<button type="button" onclick="fn_del()">삭제</button>
				</td>
			</tr>
		</table>
	</body>
</html>

- http://localhost:3000/static/emp.html


const express = require('express');
const app = express();
const port = 3000;

const bodyParser = require('body-parser');
app.use(bodyParser.json());	// json 등록
app.use(bodyParser.urlencoded({ extended : false })); // URL-encoded 등록

app.set('view engine', 'ejs');
app.set('views', './views');

app.use('/static', express.static('static'));

const DaoEmp = require('./daoemp.js');
const de = new DaoEmp();

app.get('/', (req, res) => {
	res.redirect("/static/emp.html");
});

app.post('/axois.ajax', (req, res) => {
	var e_id = req.body.e_id;
	console.log("e_id : " + e_id);
	var myjson = {'msg' : 'ok2'};
	res.json(myjson);
});

app.post('/selectlist.ajax', (req, res) => {
	var list = de.selectList();
	var data = {
		'list' : list
	};
	res.json(data);
});

app.post('/select.ajax', (req, res) => {
	var e_id = req.body.e_id;
	var vo = de.select(e_id);
	var data = {
		'vo' : vo
	};
	res.json(data);
});

app.listen(port, () => {
	console.log(`Example app listening on port ${port}`);
});
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS01</title>
		<script src="jquery-3.7.1.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/3.6.19/fetch.min.js" integrity="sha512-XVBqknFNWcPmY+09EHhvhcZChBukN5ofG0hSD6HxrlaRJvPpKArrzs7EE64Tu3d15Ills2RS7qluokksKDyu/Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
		<script>
			function setList(list){
	            var txt = "";
	            for(var i=0; i < list.length; i++) {
	            	var vo = list[i];
	            	var e_id = vo.e_id;
	            	var e_name = vo.e_name;
	            	var gen = vo.gen;
	            	var addr = vo.addr;
	            	txt += `
	            		<tr>
							<th><a href='javascript:fn_select("${e_id}")'>${e_id}</a></th>
							<th>${e_name}</th>
							<th>${gen}</th>
							<th>${addr}</th>
						</tr>
	            	`;
	            }
	            $("#mytbody").html(txt);
			}
		
			function fn_selectlist(){
				axios.post('/selectlist.ajax', {})
				.then(function(res) {
				    console.log(res.data.list);
					var list = res.data.list;
					setList(list);
				})
			}
			
			function fn_select(e_id){
				axios.post('/select.ajax', {
					'e_id' : e_id
				})
				.then(function(res) {
				    console.log(res.data.vo);
				    var vo = res.data.vo;
				    $("#e_id").val(vo.e_id);
		            $("#e_name").val(vo.e_name);
		            $("#gen").val(vo.gen);
		            $("#addr").val(vo.addr);
				})
			}
			
			$(function(){
				fn_selectlist();
			});
		</script>
	</head>
	<body>
		EMP_HTML
		<table border="1">
			<colgroup>
				<col width="25%" />
				<col width="25%" />
				<col width="25%" />
				<col width="25%" />
			</colgroup>
			<thead>
				<tr>
					<th>사원번호</th>
					<th>이름</th>
					<th>성별</th>
					<th>주소</th>
				</tr>
			</thead>
			<tbody id="mytbody">
				<tr>
					<td colspan="4">검색된 데이터가 없습니다</td>
				</tr>
			</tbody>
		</table>
		<br />
		<hr />
		<br />
		<table border="1">
			<colgroup>
				<col width="30%" />
				<col width="70%" />
			</colgroup>
			<tr>
				<td>사번</td>
				<td>
					<input type="text" id="e_id" name="e_id" />
				</td>
			</tr>
			<tr>
				<td>이름</td>
				<td>
					<input type="text" id="e_name" name="e_name" />
				</td>
			</tr>
			<tr>
				<td>성별</td>
				<td>
					<input type="text" id="gen" name="gen" />
				</td>
			</tr>
			<tr>
				<td>주소</td>
				<td>
					<input type="text" id="addr" name="addr" />
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<button type="button" onclick="fn_add()">추가</button>
					<button type="button" onclick="fn_mod()">수정</button>
					<button type="button" onclick="fn_del()">삭제</button>
				</td>
			</tr>
		</table>
	</body>
</html>


const express = require('express');
const app = express();
const port = 3000;

const bodyParser = require('body-parser');
app.use(bodyParser.json());	// json 등록
app.use(bodyParser.urlencoded({ extended : false })); // URL-encoded 등록

app.set('view engine', 'ejs');
app.set('views', './views');

app.use('/static', express.static('static'));

const DaoEmp = require('./daoemp.js');
const de = new DaoEmp();

app.get('/', (req, res) => {
	res.redirect("/static/emp.html");
});

app.post('/axois.ajax', (req, res) => {
	var e_id = req.body.e_id;
	console.log("e_id : " + e_id);
	var myjson = {'msg' : 'ok2'};
	res.json(myjson);
});

app.post('/selectlist.ajax', (req, res) => {
	var list = de.selectList();
	var data = {
		'list' : list
	};
	res.json(data);
});

app.post('/select.ajax', (req, res) => {
	var e_id = req.body.e_id;
	var vo = de.select(e_id);
	var data = {
		'vo' : vo
	};
	res.json(data);
});

app.post('/insert.ajax', (req, res) => {
	var e_id = req.body.e_id;
	var e_name = req.body.e_name;
	var gen = req.body.gen;
	var addr = req.body.addr;
	console.log(e_id, e_name, gen, addr);
	var cnt = de.insert(e_id, e_name, gen, addr);
	var data = {
		'cnt' : cnt
	};
	res.json(data);
});

app.post('/update.ajax', (req, res) => {
	var e_id = req.body.e_id;
	var e_name = req.body.e_name;
	var gen = req.body.gen;
	var addr = req.body.addr;
	console.log(e_id, e_name, gen, addr);
	var cnt = de.update(e_id, e_name, gen, addr);
	var data = {
		'cnt' : cnt
	};
	res.json(data);
});

app.post('/delete.ajax', (req, res) => {
	var e_id = req.body.e_id;
	var cnt = de.delete(e_id);
	var data = {
		'cnt' : cnt
	};
	res.json(data);
});

app.listen(port, () => {
	console.log(`Example app listening on port ${port}`);
});
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS01</title>
		<script src="jquery-3.7.1.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/3.6.19/fetch.min.js" integrity="sha512-XVBqknFNWcPmY+09EHhvhcZChBukN5ofG0hSD6HxrlaRJvPpKArrzs7EE64Tu3d15Ills2RS7qluokksKDyu/Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
		<script>
			function setList(list){
	            var txt = "";
	            for(var i=0; i < list.length; i++) {
	            	var vo = list[i];
	            	var e_id = vo.e_id;
	            	var e_name = vo.e_name;
	            	var gen = vo.gen;
	            	var addr = vo.addr;
	            	txt += `
	            		<tr>
							<th><a href='javascript:fn_select("${e_id}")'>${e_id}</a></th>
							<th>${e_name}</th>
							<th>${gen}</th>
							<th>${addr}</th>
						</tr>
	            	`;
	            }
	            $("#mytbody").html(txt);
			}
		
			function fn_selectlist(){
				axios.post('/selectlist.ajax', {})
				.then(function(res) {
				    console.log(res.data.list);
					var list = res.data.list;
					setList(list);
				})
			}
			
			function fn_select(e_id){
				axios.post('/select.ajax', {
					'e_id' : e_id
				})
				.then(function(res) {
				    console.log(res.data.vo);
				    var vo = res.data.vo;
				    $("#e_id").val(vo.e_id);
		            $("#e_name").val(vo.e_name);
		            $("#gen").val(vo.gen);
		            $("#addr").val(vo.addr);
				})
			}
			
			function fn_add(){
				axios.post('/insert.ajax', { 
					'e_id' : $("#e_id").val(),
					'e_name' : $("#e_name").val(),
					'gen' : $("#gen").val(),
					'addr' : $("#addr").val()
				})
				.then(function(res) {
				    console.log(res);
				    var cnt = res.data.cnt;
		            if(cnt == 1){
		            	fn_selectlist();
			            $("#e_id").val("");
			            $("#e_name").val("");
			            $("#gen").val("");
			            $("#addr").val("");
		            }else {
		            	alert("수정 도중 문제가 생겼습니다.");
		            }
				})
			}
			
			function fn_mod(){
				axios.post('/update.ajax', { 
					'e_id' : $("#e_id").val(),
					'e_name' : $("#e_name").val(),
					'gen' : $("#gen").val(),
					'addr' : $("#addr").val()
				})
				.then(function(res) {
				    console.log(res);
				    var cnt = res.data.cnt;
		            if(cnt == 1){
		            	fn_selectlist();
			            $("#e_id").val("");
			            $("#e_name").val("");
			            $("#gen").val("");
			            $("#addr").val("");
		            }else {
		            	alert("수정 도중 문제가 생겼습니다.");
		            }
				})
			}
			
			function fn_del(){
				var flag = confirm("한번 지워진 데이터는 복구 불가합니다. 그래도 지우시렵니까?");
				if(!flag){
					return;
				}
				axios.post('/delete.ajax', {
					'e_id' : $("#e_id").val()
				})
				.then(function(res) {
					console.log(res);
				    var cnt = res.data.cnt;
		            if(cnt == 1){
		            	fn_selectlist();
			            $("#e_id").val("");
			            $("#e_name").val("");
			            $("#gen").val("");
			            $("#addr").val("");
		            }else {
		            	alert("삭제 도중 문제가 생겼습니다.");
		            }
				})
			}
			
			$(function(){
				fn_selectlist();
			});
		</script>
	</head>
	<body>
		EMP_HTML
		<table border="1">
			<colgroup>
				<col width="25%" />
				<col width="25%" />
				<col width="25%" />
				<col width="25%" />
			</colgroup>
			<thead>
				<tr>
					<th>사원번호</th>
					<th>이름</th>
					<th>성별</th>
					<th>주소</th>
				</tr>
			</thead>
			<tbody id="mytbody">
				<tr>
					<td colspan="4">검색된 데이터가 없습니다</td>
				</tr>
			</tbody>
		</table>
		<br />
		<hr />
		<br />
		<table border="1">
			<colgroup>
				<col width="30%" />
				<col width="70%" />
			</colgroup>
			<tr>
				<td>사번</td>
				<td>
					<input type="text" id="e_id" name="e_id" />
				</td>
			</tr>
			<tr>
				<td>이름</td>
				<td>
					<input type="text" id="e_name" name="e_name" />
				</td>
			</tr>
			<tr>
				<td>성별</td>
				<td>
					<input type="text" id="gen" name="gen" />
				</td>
			</tr>
			<tr>
				<td>주소</td>
				<td>
					<input type="text" id="addr" name="addr" />
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<button type="button" onclick="fn_add()">추가</button>
					<button type="button" onclick="fn_mod()">수정</button>
					<button type="button" onclick="fn_del()">삭제</button>
				</td>
			</tr>
		</table>
	</body>
</html>

- http://localhost:3000/static/emp.html



'대덕인재개발원 > 대덕인재개발원_파이썬 프로그래밍' 카테고리의 다른 글

231120_React.js 개론  (0) 2023.11.20
00_기타 자료실  (0) 2023.11.16
231116_Node.js 개론 2  (0) 2023.11.16
231115_Node.js 개론 1  (0) 2023.11.15
231114_Django 개론 5  (0) 2023.11.14