웹프로그래밍/node.js
http 모듈
hyun_jo_o
2019. 8. 8. 16:49
node는 서버가 아니고 런타임이다.
http모듈이 서버 역할을 한다.
const http = require('http');
// http모듈이 서버 역할을 한다.
// node는 서버가 아니고 런타임
//이벤트 명은 써줄 필요가 없다.
http.createServer((req, res) => {
console.log('서버 실행');
res.write('<h1>Hello Node!</h1>');
res.write('<h2>Hello JS!</h2>');
res.write('<h2>Hello JS!</h2>');
res.end('<p>Hello Server!</p>');
}).listen(8080, () => {
console.log('8080번 포트에서 서버 대기중입니다.');
});
//http 기본포트(80)
//https (443)
//기본 포트는 생략가능
//포트가 다르면 호스트가 같더라도 다른 사이트 처럼 동작할 수 있다.
응답으로 파일 읽어보내기
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
console.log('서버 실행');
fs.readFile('./server2.html', (err, data) => { //파일로 읽어오는 코드
if (err) {
throw err;
}
res.end(data);
});
}).listen(8080);
server.on('listening', () => {
console.log('8080번 포트에서 서버 대기중입니다.');
});
//에러 내용을 확인하는 이벤트 리스너
server.on('error', (error) => {
console.error(error);
});
server도 이벤트기반으로 동작하기 때문에 이벤트리스너를 붙힐 수 있다.
노드가 에러에 취약하기 때문에 에러 내용을 확인하는 이벤트리스너도 쓸 수 있다.
res.write로 모든 html을 보내줄 수 없기 때문에 파일로 읽어오게 된다.