http 프로토콜 ( HyperText Transfer Protocol )
하이퍼텍스트 전송 프로토콜로 웹 상에서 데이터를 주고 받기 위한 일종의 규약(프로토콜) 입니다.
클라이언트가 서버로 요청을 보냄
서버는 요청을 처리하고 클라이언트로 응답을 보냄
요청(requsest), 응답(response)
write로 응답내용을 작성
end로 응답 마무리
writeHead에 Header에 정보를 넣을 수 있습니다.
Header의 Content-Type은 응답하는 본문의 타입을 지정하는 역할
브라우저 마다 이게 무슨파일인지 알아야 읽는경우가 있기때문에 Header에 정보를 담아 주는것이 좋다.
- text/plain: 일반 텍스트 데이터를 나타냅니다.
- text/html: HTML 문서를 나타냅니다.
- text/css: CSS 스타일시트를 나타냅니다.
- application/json: JSON 데이터를 나타냅니다.
- application/xml: XML 데이터를 나타냅니다.
- image/jpeg, image/png, image/gif: 각각 7 .JPEG, PNG, GIF 이미지를 나타냅니다.
- multipart/form-data: 파일 업로드와 같은 멀티파트 데이터를 나타냅니다.
const http = require("http")
const server = http.createServer((req, res)=>{
res.writeHead(200, { 'Content-Type': "text/html; charset=utf-8"})
res.write('<h1>Hello</h1>')
res.end()
}).listen(8080, ()=>{
console.log('8080번 포트에 연결되었습니다.')
})
이벤트 메서드로 서버연결 성공 시 콜백함수
그리고 실패시에 대한 것으로 나누어 사용가능
listening과 error 이벤트를 붙일 수 있음.
const http = require('http')
const server = http.createServer((req, res)=>{
res.writeHead(200, { 'Content-Type': "text/html; charset=utf-8"})
res.write('<h1>Hello</h1>')
})
server.listen(8080)
server.on('lisening', () => {
console.log('서버가 연결되었습니다.')
})
server.on('error', (error)=>{
console.error(error)
})