node.js 수업

node.js-1 server로 데이터 전달( html, json, xml,parameter)

줄라이퍼스트 2020. 2. 21. 14:48

※  1. 응답형식에 따른 웹 서비스 - html형태

// 모듈 추출
var http = require('http');
var express = require('express');


// 웹 서버 생성
var app = express();



// 변수를 선언합니다.

var items=[{
    name: '우유',
    price: '2000'
},{
    name:'홍차',
    price: '5000'
},{
    name:'커피',
    price:'5000'
}];

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);

});



/* 
    1. static 선언 : 'public' folder를 static으로 선언
    static으로 선언하면, node.js가 자동으로
    public folder에 있는 html, image file, css, js등을 인식함

    2. web browser에서 홈페이지 주소만 부르면(http://127.0.0.1:52273)
    web server는 홈페이지 주소에, index.html 등의 기본 파일이 있으면 index.html을 자동 실행함

    3.  http://127.0.0.1:52273/index.html을 실행함
        http://127.0.0.1:52273/product

*/
app.use(express.static('public'));
//app.use(app.router);
// /a에서 /가 root를 의미
//  root URL : http://127.0.0.1:52273
// app.all : app.get, app.post, app.put, app.delete 모두 가능



app.all('/a',function(request, response){
    response.send('<h1>Page A</h1>');
 
});

app.all('/b',function(request, response){
    response.send('<h1>Page B</h1>');
 
});

app.all('/c',function(request, response){
    response.send('<h1>Page C</h1>');
 
});

app.use(function(request, response){    
    response.send('<h1>안녕하세요~!</h1><h2>반갑습니다~!</h2>');
});
// 웹 서버 실행
http.createServer(app).listen(52273,function(){
    console.log('Server running at http://127.0.0.1:52273');
});

※  1. 실행화면(html)

 

1. 실행화면 - node.js로 실행한 후 url 주소 뒤에  /data.html을 추가하면 html 형식으로 나오는 것을 볼 수 있다

 

※  2. 응답형식에 따른 웹 서비스 - json형태

 

// 모듈 추출
var http = require('http');
var express = require('express');


// 웹 서버 생성
var app = express();



// 변수를 선언합니다.

var items=[{
    name: '우유',
    price: '2000'
},{
    name:'홍차',
    price: '5000'
},{
    name:'커피',
    price:'5000'
}];

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);
});
/********************************************************/

/* 
    1. static 선언 : 'public' folder를 static으로 선언
    static으로 선언하면, node.js가 자동으로
    public folder에 있는 html, image file, css, js등을 인식함

    2. web browser에서 홈페이지 주소만 부르면(http://127.0.0.1:52273)
    web server는 홈페이지 주소에, index.html 등의 기본 파일이 있으면 index.html을 자동 실행함

    3.  http://127.0.0.1:52273/index.html을 실행함
        http://127.0.0.1:52273/product

*/
app.use(express.static('public'));
//app.use(app.router);
// /a에서 /가 root를 의미
//  root URL : http://127.0.0.1:52273
// app.all : app.get, app.post, app.put, app.delete 모두 가능



app.all('/a',function(request, response){
    response.send('<h1>Page A</h1>');
 
});

app.all('/b',function(request, response){
    response.send('<h1>Page B</h1>');
 
});

app.all('/c',function(request, response){
    response.send('<h1>Page C</h1>');
 
});

app.use(function(request, response){    
    response.send('<h1>안녕하세요~!</h1><h2>반갑습니다~!</h2>');
});
// 웹 서버 실행
http.createServer(app).listen(52273,function(){
    console.log('Server running at http://127.0.0.1:52273');
});

 

※  2. 응답형식에 따른 웹 서비스 - (json)

 

2. 실행화면 - node.js로 실행한 후 url 주소 뒤에  /data.json을 추가하면 json 형식으로 나오는 것을 볼 수 있다

 

※  3. xml형태

 

// 모듈 추출
var http = require('http');
var express = require('express');


// 웹 서버 생성
var app = express();



// 변수를 선언합니다.

var items=[{
    name: '우유',
    price: '2000'
},{
    name:'홍차',
    price: '5000'
},{
    name:'커피',
    price:'5000'
}];

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.send(output);

});
/**************************************************************/

/* 
    1. static 선언 : 'public' folder를 static으로 선언
    static으로 선언하면, node.js가 자동으로
    public folder에 있는 html, image file, css, js등을 인식함

    2. web browser에서 홈페이지 주소만 부르면(http://127.0.0.1:52273)
    web server는 홈페이지 주소에, index.html 등의 기본 파일이 있으면 index.html을 자동 실행함

    3.  http://127.0.0.1:52273/index.html을 실행함
        http://127.0.0.1:52273/product

*/
app.use(express.static('public'));
//app.use(app.router);
// /a에서 /가 root를 의미
//  root URL : http://127.0.0.1:52273
// app.all : app.get, app.post, app.put, app.delete 모두 가능



app.all('/a',function(request, response){
    response.send('<h1>Page A</h1>');
 
});

app.all('/b',function(request, response){
    response.send('<h1>Page B</h1>');
 
});

app.all('/c',function(request, response){
    response.send('<h1>Page C</h1>');
 
});

app.use(function(request, response){    
    response.send('<h1>안녕하세요~!</h1><h2>반갑습니다~!</h2>');
});
// 웹 서버 실행
http.createServer(app).listen(52273,function(){
    console.log('Server running at http://127.0.0.1:52273');
});

 

 

※  3. 실행화면(xml)

 

 

3. 실행화면 - node.js로 실행한 후 url 주소 뒤에  /data.xml을 추가하면 xml형식으로 나오는 것을 볼 수 있다

 

 

※  3-1. 실행화면(xml)

 

esponse . setHeader  ( "Content-Type" , "text/xml" ) 추가하면 xml 형식으로도 볼 수 있다.

※  4. 요청 매개변수에 따른 웹 서비스 - parameter 형태

이부분 추가

 

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>');
});

※  4. 실행화면(parameter)

 

get방식으로 전송되어 name과 region을 확인 할 수 있다.

※  5. 요청 형식에 따른 웹 서비스 - GET/products형태

이부분 추가

/////1.//////
app.get('/products', function(request,response){
    response.send(items);
});

/////2.//////
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 : '존재하지 않는 데이터입니다.!'
       });
   }
});

※  5. 실행화면

 

5. 실행화면 - get방식으로 전송되어온 items를 확인 할 수 있다.

 

※  5. 요청 형식에 따른 웹 서비스 - POST/products형태

 

// 모듈 추출
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');

// 웹 서버 생성
var app = express();


// 변수를 선언합니다.

var items=[{
    name: '우유',
    price: '2000'
},{
    name:'홍차',
    price: '5000'
},{
    name:'커피',
    price:'5000'
}];

app.use(bodyParser.urlencoded({extended: false}));

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
    });
 });



// 웹 서버 실행
http.createServer(app).listen(8001,function(){
    console.log('Server running at http://127.0.0.1:8001');
});

 

※  5. 실행화면- POST/products형태

 

5-1. 실행화면 - GET방식을 이용하였을 때

 

5-2. 실행화면 - POST 방식으로 Body 부분 추가

 

5-2. 실행화면 - POST 방식으로 smothie가 추가된 것을 볼 수 있음

※  포스트맨(POSTMAN)을 이용하여 확인

 

포스트맨을 이용하여 확인해보자

 

1. html 형식

 

 

 

2. json 형식

 

 

3. xml 형식

 

 

 

4. parameter 형식

 

 

5. GET/products형태