이번엔 http모듈에서 get 파라미터와 post 의 데이터 값을 구하는 예제 입니다.
1. Get 파라미터 구하기
server.js 소스
1 2 3 4 5 6 7 8 9 10 11 | <span style= "font-size: 10pt;" > var http = require( "http" );
var url = require( "url" );
http.createServer( function (req, res) {
var query = url.parse(req.url, true ).query;
console.log(query);
}).listen(8080, function (){
console.log( "server running" );
});
</span>
|
브라우져로 url에 파라미터를 주면 ? 이후부터 json방식으로 콘솔에 찍힙니다.
브라우져 접속 예) http://127.0.0.1:8080?titleId=597447&weekday=sat

콘솔창에 다음과 같이 나옵니다.

2. post 값 구하기
post는 form 이 필요하기 때문에 html 파일이 필요합니다.
server.js 소스
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <span style= "font-size: 10pt;" > var http = require( "http" );
var fs = require( "fs" );
http.createServer( function (req, res) {
if (req.method == 'POST' ){
req.on( 'data' , function (data) {
console.log(data.toString());
});
}
fs.readFile(__dirname + '/' + req.url + '.html' , function (err, data) {
res.writeHead(200, { 'Content-Type' : 'text/html' });
res.end(data);
});
}).listen(8080, function (){
console.log( "server running" );
});
</span>
|
post.html 파일 소스
<html>
<head>
</head>
<body>
<form method="post">
<input type="text" name="id"/>
<input type="password" name="password"/>
<input type="submit"/>
</form>
</body>
</html>
해당 파일을 실행후 브라우저에 http://127.0.0.1:8080/post 로 접속 후 form 에 데이터를 넣은후 제출 버튼을 눌러주면 서버의 콘솔에 해당 값이 찍힙니다.


출처: http://uiandwe.tistory.com/953