본문 바로가기
IT/NodeJS

URL 라우팅및 데이터 전달방식 예제들...POST 방식으로 json 형식 사용예등

by 골든크랩 2022. 7. 18.
728x90
반응형

 

var express = require('express');
var app = express();
app.use(express.urlencoded({extended:true}));

//get - request.query 
//파라미터 
//http://127.0.0.1:4000/a/3
app.get("/a/:id", function(request, response, next){
 console.log( request.params["id"]);
 console.log( request.params.id);

 response.send('a 입니다');
});

//http://127.0.0.1:4000/b/3
app.get("/b/:page", function(request, response, next){
 console.log( request.params["page"]);
 response.send('b 입니다');
});

//http://127.0.0.1:4000/c/korea
app.get("/c/:keyword", function(request, response, next){
 console.log( request.params["keyword"]);
 response.send('c 입니다');
});


// http://127.0.0.1:4000/add/4/5
app.get("/add/:x/:y", (req, res)=>{
 var x = parseInt(req.params.x);
 var y = parseInt(req.params.y);

 res.send(`${x} + ${y} = ${x+y}`);
});


// http://127.0.0.1:4000/gugudan/4
app.get("/gugudan/:dan/", (req, res)=>{
 //res.writeHead(200, {'Content-Type':'text/plain'}); //- 기본값, html 태그가 안먹는 형식

 res.writeHead(200, {'Content-Type':'text/html'});
 var dan = parseInt(req.params.dan);
 for(i=1; i<=9; i++)
 {
  res.write(`<p>${dan} X ${i} = ${dan*i}</p>`);
 }
 res.end();
});

//post 방식일때 이전에는 body-parser를 사용했었음
//현재는 express에 내장되어있어서 별도 처리가 필요없다 
//app.use(express.urlencoded({extended:true}));
/*
리눅스 버전 테스트
curl -d '{"mysql":"mysqlidpwd", "filelocation":"/home/koko/.nodeProj/mysql/xxx.file"}' -H "Content-Type: application/json" -X POST http://localhost:4000/data

윈도우 버전 테스트
curl -d "{""mysql"":""mysqlidpwd"", ""filelocation"":""/home/koko/.nodeProj/mysql/xxx.file""}" -H "Content-Type: application/json" -X POST http://localhost:4000/data
*/
app.use(express.json());
app.post("/data", (req, res)=>{
  var mysql = req.body.mysql;
  console.log(mysql);

  var filelocation = req.body.filelocation;
  console.log(filelocation);

  console.log(req.body);
  res.write("success");
  res.end();
});



app.listen(4000, function () {
  console.log('Example app listening on port 4000!');
});

728x90
반응형

댓글