
1. 개요
Node.js에서 http 모듈로 웹으로 요청 URL에 따른 다양한 서비스를 분기하는 예제이다.
2. 사용법
먼저 http 모듈과 fs 모듈을 선언한다.
var http = require('http');
var fs = require('fs');
요청URL 에 대한 각각의 request.url에 대해서 if ~ else ~ 문으로 분기를 하여 처리한다.
if (request.url == "/")
{
response.writeHead(200, { 'Content-Type' : 'text/html; charset=utf-8' });
…(중략)…
}
else if (request.url == "/about")
{
response.writeHead(200, { 'Content-Type' : 'text/html; charset=utf-8' });
…(중략)…
}
else if (request.url == "/image")
{
…(중략)…
}
else if (request.url == "/song")
{
…(중략)…
}
else if (request.url == "/moive")
{
…(중략)…
}
else if (request.url == "/down")
{
…(중략)…
}
else
{
response.end("<h1>404 error<br> File not found</h1>");
}
3. 예제
아래는 전체 코드이다.
/** request */
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
if (request.url == "/")
{
response.writeHead(200, { 'Content-Type' : 'text/html' });
response.write("<h1>Main page</h1>");
response.write('<hr>');
response.write('<footer style="text-align: center;">');
response.write(' <a href="http://blog.naver.com/agapeuni">" target="_blank" class="con_link">">">http://blog.naver.com/agapeuni</a>');
response.write('</footer>');
response.end();
}
else if (request.url == "/about")
{
response.writeHead(200, { 'Content-Type' : 'text/html; charset=utf-8' });
response.write("<h1>About page</h1>");
response.write('<hr>');
response.write('<footer style="text-align: center;">');
response.write(' <a href="http://blog.naver.com/agapeuni">" target="_blank" class="con_link">">">http://blog.naver.com/agapeuni</a>');
response.write('</footer>');
response.end();
}
else if (request.url == "/image")
{
fs.readFile('image.jpg', function(err, data) {
response.writeHead(200, { 'Content-Type' : 'image/jpeg' });
response.write(data);
response.end();
});
}
else if (request.url == "/song")
{
fs.readFile('song.mp3', function(err, data) {
response.writeHead(200, { 'Content-Type' : 'audio/mpeg' });
response.write(data);
response.end();
});
}
else if (request.url == "/moive")
{
fs.readFile('movie.mp4', function(err, data) {
response.writeHead(200, { 'Content-Type' : 'video/mp4' });
response.write(data);
response.end();
});
}
else if (request.url == "/down")
{
fs.readFile('movie.mp4', function(err, data) {
response.writeHead(200, { 'Content-Type' : 'video/mp4', 'Content-Disposition' : 'attachment;filename=movie.mp4' });
response.write(data);
response.end();
});
}
else
{
response.end("<h1>404 error<br> File not found</h1>");
}
}).listen(1337, '127.0.0.1');
console.log('http://127.0.0.1:1337/');



728x90
'■ Front-End ■ > Node.js' 카테고리의 다른 글
[Node.js] json 파일을 직접 불러와서 사용해 보자. (0) | 2023.02.26 |
---|---|
[Node.js] http 모듈로 웹으로 GET/POST를 서비스해보자. (0) | 2023.02.26 |
[Node.js] http 모듈로 text와 html을 브라우저에 표시해보자. (0) | 2023.02.26 |
[Node.js] socket.io 모듈을 사용하여 소켓통신을 구현해 보자. (0) | 2023.02.26 |
[Node.js] net 모듈을 사용하여 네트워킹을 해보자. (0) | 2023.02.26 |
댓글