기록해! 정리해!

응답과 응답형식 (html, json, xml ) 본문

자바스크립트

응답과 응답형식 (html, json, xml )

zsuling 2022. 9. 29. 10:45
const  http = require('http');
const  express = require('express');

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

const  app = express();

app.use(express.logger());
app.use(express.bodyParser());
app.use(express.static('public'));
app.use(app.router);

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

app.all('/data.html', (request, response) => {
  var output="";
  items.forEach( (item)=>{
     output += item.name + ":" + item.price +"<br>" ;
  });
   
  response.send(output);

});

app.all('/data.json', (request, response) =>{
  response.send(items);
});

app.all('/data.xml', (request, response) => {
  var output="";
  output += '<?xml version="1.0" encoding="UTF-8" ?>';
  output += '<products>' ;
  items.forEach( (item) =>{
    output += '<product>' ;
    output += '<name>' + item.name + '</name>' ;
    output += '<price>' + item.price + '</price>' ;
    output += '</product>' ;
  });
  output += '</products>' ;
  response.type('text/xml');
  response.send(output);
});

app.use( ( request,  response ) => {
  response.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
  response.end('<div align=center><h1> 서버 접근을 환영합니다.!!!  </h1></div');
});

http.createServer(app).listen(52273, () => {
    console.log ('Server  Running  at  http://127.0.0.1:52273');
})

'자바스크립트' 카테고리의 다른 글

Postman 사용하기  (0) 2022.09.29
Node.js -ppt 실습 (1)  (0) 2022.09.28
Node.js 다운로드 + 테스트하기  (0) 2022.09.28
Comments