JSON, XML, HTML 로 반환하기
- Items 배열의 값을 'JSON, XML, HTML' 타입으로 반환하는 예시
var items =[
{name:"우유",
price:200},
{name:"홍차",
price:700},
{name:"커피",
price:300},
]
1. JSON 타입
var http = require('http')
var express = require('express')
var app = express()
app.use(express.static('public'))
app.use(app.router)
//json 타입
app.all("/data.json", function(req, res){
res.send(items)
})
http.createServer(app).listen(52273, function(){
console.log("서버 가동 완료. http://127.0.0.1:52273")
})
2. XML 타입
var http = require('http')
var express = require('express')
var app = express()
app.use(express.static('public'))
app.use(app.router)
//xml 타입
app.all("/data.xml", function(req, res){
res.type("text/xml");
var output = "<products>";
items.forEach(function(item){
output += "<product>";
output += "<name>"+ item.name +"</name>";
output += "<price>"+ item.price +"</price>";
output += "</product>";
})
output += "</products>";
res.send(output);
})
http.createServer(app).listen(52273, function(){
console.log("서버 가동 완료. http://127.0.0.1:52273")
})
3. HTML 타입
var http = require('http')
var express = require('express')
var app = express()
app.use(express.static('public'))
app.use(app.router)
//html 타입
app.all("/data.html", function(req, res){
var output="";
output +="<html>";
output +="<body>";
items.forEach(function(item){
output += "<div>";
output += "<h1>" + item.name+ "<h1>";
output += "<h2>" + item.price+ "<h2>";
output += "</div>";
})
output +="</body>";
output +="</html>";
res.send(output);
})
http.createServer(app).listen(52273, function(){
console.log("서버 가동 완료. http://127.0.0.1:52273")
})
반응형
'개발 > Node.js' 카테고리의 다른 글
Node.js ) 파라미터 넘기고 null 처리(isNaN) (0) | 2022.07.27 |
---|
댓글