nodejs 트래픽 라우팅, 파일 서비스, 미들웨어
DESCRIPTION
Nodejs 트래픽 라우팅, 파일 서비스, 미들웨어 connect http-proxyTRANSCRIPT
nodejs
트래픽 라우팅, 파일 서비스, 미들웨어
간단한 파일 서버
간단한 정적 파일 서버 만들기
1. HTTP서버를 생성 -> 대기
2. 요청 URL을 파싱하여 파일 위치 결정
3. 파일이 존재하는지 확인
4. 파일이 존재->파일열기
5. 파일이 없으면, 적절하게 응답
6. 응답
7. 다음요청을 대기
http.createServer(function (req, res) {
pathname = base + req.url;
console.log(pathname);
path.exists(pathname, function(exists) {
if (!exists) {
} else {
});
}).listen(8124);
console.log('Server running at 8124/');
if (!exists) {
res.writeHead(404);
res.write('Bad request 404\n');
res.end();
}
else { res.setHeader('Content-Type', 'text/html'); // 200 status - found, no errors res.statusCode = 200; // create and pipe readable stream var file = fs.createReadStream(pathname); file.on("open", function() { file.pipe(res); }); file.on("error", function(err) { console.log(err); }); }
• __dirname : 현재 디렉토리
• 윈도우에서는 base를 ‘./’
• 멀티미디어는 node-mime모듈
미들웨어
미들웨어?
양 쪽을 연결하여 데이터를 주고 받을 수 있도록
중간에서 매개 역할을 하는 소프트웨어
JSGI / Connect
Connect
- 대표적인 nodejs 미들웨어
- Express와 연동가능
- 설치 : npm install connect
- Express 4.0에서는 더 이상 지원 X http://expressjs.com/4x/api.html#middleware
Simple connect
http.createServer(connect()
.use(connect.favicon())
.use(connect.logger())
.use(function(req,res){
res.end(‘hello world’);
})
).listen(8124);
대표적 connect번들
• connect.static
• Connect.logger
• Connect.parseCookie
• Connect.parseSession
connect.static
.use(connect.static(__dirname), {redirect:true})
- 브라우저 캐싱, 잘못된 형식의 URL보호 등
Connect.logger
.use(connect.logger(
{format : ‘dev’,
stream : writeStream})
- 요청들에 대한 로그를 스트림에 기록
- 용도에 맞는 로그 모드 제공(default, short, tiny, dev)
Connect.parseCookie
.use(connect.cookieParser())
.use(connect.kookieSession())
- 다음장에 예제
사용자 정의 함수를 이용한
var app = connect()
.use(connect.logger('dev'))
.use(connect.cookieParser('mumble'))
.use(connect.cookieSession({key : 'tracking'}))
.use(clearSession)
.use(trackUser);
사용자 정의 함수를 이용한
function clearSession(req, res, next) { if ('/clear' == req.url) { req.session = null; res.statusCode = 302; res.setHeader('Location', '/'); res.end(); } else { next(); } } next()는 미들웨어가 현재 요청을 처리 하지 않는경우, 오류가 있는경우
라우터
라우터
- 한 소스로부터 무언가를 받아서 다른 것으로 전달
- 대표적으로는 crossroads
- http://yourplace.org/article/urllllll http://yourplace.org/node/174
Crossroads대표적 모듈
- addRoute 라우팅 패턴설정
- Parse 문자열 파싱 후, 적절한 경로로 보냄
- matched.add 라우팅 핸들러를 대응하는 경로에 매핑
Crossroads대표적 모듈
http.createServer(function(req,res) {
crossroads.parse(req.url);
res.end('and that\'s all\n');
}).listen(8124);
Crossroads대표적 모듈
crosroads.addRoute('/category/{type}/:pub:/:id:', function(type,pub,id){
if (!id && !pub){
} else if (!id) {
} else {
}
});
http://... /category/history
http://... /category/history/journal
http://... /category/history/journal/123
프록시
프록시
- 여러 개의 다른 위치에서 요청된 내역을 하나의 서버로 라우팅 하는 방법
- 로드밸런싱, 캐시, 보안, 원래의 요청자를 감추는 목적 때문에 사용
http-proxy
httpProxy.createServer(8124, ‘localhost’).listen(8000)
//8000번 포트에서 대기하다가 8124로 전달
- 정방향, 역방향 프록시 제공
- 웹소켓, HTTPS지원