CRUD 실습 예제
※ 1. 데이터 요청방식 (get())
CRUD_html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://code.jquery.com/jquery-3.1.1.js"></script>
<script>
$(document).ready(function(){
$("#get").click(function(){
$.ajax({
url:'http://127.0.0.1:8003/products',
// type : get, post, put, delete
type: 'get',
// data type
dataType:'text',
success: function(data){
$("#output").val(data);
}
});
});
});
</script>
</head>
<body>
<button id = "get">GET</button>
<button id = "post">POST</button>
<button id = "put">PUT</button>
<button id = "delete">DELETE</button>
<h1>input</h1>
<label>name :</label><input id="name"/>
<label>price :</label><input id="price"/>
<h1>output</h1>
<textarea id="output" class="res_menu" disabled="disabled" cols="40" rows="5"></textarea>
</body>
</html>
server.js
// 모듈 추출
var http = require('http');
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
// 변수를 선언합니다.
var items=[{
name: '우유',
price: '2000'
},{
name:'홍차',
price: '5000'
},{
name:'커피',
price:'5000'
}];
// 웹 서버 생성
var app = express();
app.use(express.static('public2'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors());
app.all('/data.html', function(request,response){
var output ='';
output += '<!DOCTYPE html>';
output += '<html>';
output += '<head>';
output += ' <title>Data HTML</title>';
output += '</head>';
output += '<body>';
items.forEach(function(item){
output +='<div>';
output +=' <h1>'+ item.name + '</h1>';
output +=' <h2>'+ item.price + '</h2>';
output +='</div>';
});
output += "</body>";
output += "</html>";
response.send(output);
});
// json data format으로 client에게 보내는 방식
app.all('/data.json',function(request, response){
// send : 일반 javascript 오브젝트(객체)를 web browser 전송할 때 자동으로 json 형태로 변환하여 넘겨줌
response.send(items);
});
app.all('/data.xml', function(request,response){
var output ='';
output += '<?xml version="1.0" encoding="UTF-8" ?>';
output += '<products>';
items.forEach(function(item){
output +='<product>';
output +=' <name>'+ item.name + '</name>';
output +=' <price>'+ item.price + '</price>';
output +='</product>';
});
output += "</products>";
// response.type('text/xml');
response.setHeader ("Content-Type","text/xml");
response.send(output);
});
app.all('/parameter', function(request, response){
// 변수를 선언합니다.
// request.query : query string의 key를 갖고 있는 객체
var name = request.query.name;
var region = request.query.region;
// 응답합니다.
response.send ('<h1>' + name + ':' + region + '</h1>');
});
app.all('/parameter/:id', function(request, response){
// 변수를 선언합니다.
var id = request.params.id;
// 응답합니다.
response.send ('<h1>' + id + '</h1>');
});
app.get('/products', function(request,response){
response.send(items);
});
app.get('/products/:id', function(request,response){
// 변수를 선언합니다.
var id = Number(request.params.id);
if(isNaN(id)){
// 오류: 잘못된 경로
response.send({
error: '숫자를 입력하세요!'
});
}else if(items[id]){
// 정상
response.send(items[id]);
}else{
// 오류 : 요소가 없을 경우
response.send({
error : '존재하지 않는 데이터입니다.!'
});
}
});
app.post('/products', function(request,response){
// 변수를 선언합니다.
var name = request.body.name;
var price = request.body.price;
var item ={
name: name,
price: price
};
// 데이터를 추가합니다.
items.push(item);
// 응답합니다.
response.send({
message: '데이터를 추가했습니다.',
data : item
});
});
/*
웹사이트 (레스토랑 관리시스템) 만들기
- client html
- server program : 조회, 추가, 삭제, 수정
- 내용 : restaurant 이름, 메뉴, 가격
하나씩 가져오기 get을 하게되면은
*/
app.put('/products/:id', function (request, response) {
// 변수를 선언합니다.
var id = Number(request.params.id);
var name = request.body.name;
var price = request.body.price;
if (items[id]) {
// 데이터를 수정합니다.
if (name) { items[id].name = name; }
if (price) { items[id].price = price; }
// 응답합니다.
response.send({
message: '데이터를 수정했습니다.',
data: items[id]
});
} else {
// 오류: 요소가 없을 경우
response.send({
error: '존재하지 않는 데이터입니다!'
});
}
});
app.del('/products/:id',function(request,response){
// 변수를 선언합니다.
var id = Number(request.params.id);
if(isNaN(id)){
// 오류 : 잘못된 경로
response.send({
error :'숫자를 입력하세요!'
});
}else if(items[id]){
// 정상 : 데이터 삭제
items.splice(id,1);
response.send({
message : '데이터를 삭제했습니다.'
});
}else{
// 오류 : 요소가 없을 경우
response.send({
error : '존재하지 않는 데이터 입니다.!'
});
}
});
// 웹 서버 실행
http.createServer(app).listen(8003,function(){
console.log('Server running at http://127.0.0.1:8003');
});
※ 1. 실행화면
※ 2. 데이터 요청방식 (post())
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://code.jquery.com/jquery-3.1.1.js"></script>
<script>
$(document).ready(function(){
$("#get").click(function(){
$.ajax({
url:'http://127.0.0.1:8003/products',
// type : get, post, put, delete
type: 'get',
// data type
dataType:'text',
success: function(data){
$("#output").val(data);
}
});
});
$("#post").click(function(){
$.ajax({
url:'http://localhost:8003/products',
type: 'post',
dataType:'text',
// data : request 본문으로 server에 전달할 데이터
data:{
// 전달할 데이터도 객체로 표기
name:$("#name").val(),
price:$("#price").val()
},
success: function(data){
$("#output").val(data);
}
});
});
});
</script>
</head>
<body>
<button id = "get">GET</button>
<button id = "post">POST</button>
<button id = "put">PUT</button>
<button id = "delete">DELETE</button>
<h1>input</h1>
<label>name :</label><input id="name"/>
<label>price :</label><input id="price"/>
<h1>output</h1>
<textarea id="output" class="res_menu" disabled="disabled" cols="40" rows="5"></textarea>
</body>
</html>
※ 2. 실행화면
※ 3. 데이터 요청방식 (put(), delete())
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://code.jquery.com/jquery-3.1.1.js"></script>
<script>
$(document).ready(function(){
$("#get").click(function(){
$.ajax({
url:'http://127.0.0.1:8003/products',
// type : get, post, put, delete
type: 'get',
// data type
dataType:'text',
success: function(data){
$("#output").val(data);
}
});
});
$("#post").click(function(){
$.ajax({
url:'http://localhost:8003/products',
type: 'post',
dataType:'text',
// data : request 본문으로 server에 전달할 데이터
data:{
// 전달할 데이터도 객체로 표기
name:$("#name").val(),
price:$("#price").val()
},
success: function(data){
$("#output").val(data);
}
});
});
$("#put").click(function(){
$.ajax({
url:'http://localhost:8003/products/0',
type: 'put',
dataType:'text',
// data : request 본문으로 server에 전달할 데이터
data:{
// 전달할 데이터도 객체로 표기
name:$("#name").val(),
price:$("#price").val()
},
success: function(data){
$("#output").val(data);
}
});
});
$("#delete").click(function(){
$.ajax({
url:'http://localhost:8003/products/0',
type: 'delete',
dataType:'text',
// data : request 본문으로 server에 전달할 데이터
success: function(data){
$("#output").val(data);
}
});
});
});
</script>
</head>
<body>
<button id = "get">GET</button>
<button id = "post">POST</button>
<button id = "put">PUT</button>
<button id = "delete">DELETE</button>
<h1>input</h1>
<label>name :</label><input id="name"/>
<label>price :</label><input id="price"/>
<h1>output</h1>
<textarea id="output" class="res_menu" disabled="disabled" cols="40" rows="5"></textarea>
</body>
</html>
※ 4. 실행화면
- put()-이용
- delete()-이용
'node.js 수업' 카테고리의 다른 글
node.js-5(Ajax 사용) 데이터사용-(get(), post(), put(), delte()) (0) | 2020.02.25 |
---|---|
node.js-4 실습 (0) | 2020.02.24 |
node.js-3(Ajax 사용) XMLHttpRequest 객체 (0) | 2020.02.24 |
node.js-2 클라이언트 요청처리(put(), del()) (0) | 2020.02.24 |
node.js-1 server로 데이터 전달( html, json, xml,parameter) (0) | 2020.02.21 |