- response
require('http').createServer((request, response) =>{
response.writeHead(200, {'Content-Type' :'text/html'});
response.end('<h1>Hello World</h1>');
}).listen(5500, ()=>{
console.log('서버가 동작중입니다. http://127.0.0.1:5500');
});
//주의!! 포트넘버 확인을 꼭하기! 쓰는 툴마다 포트 넘버가 다름!! 그 포트넘버에 맞춰서 http주소 들고 와야함
response.writeHead는 응답 헤더를 설정하는 메소드이고, 여기에 전달되는 두 개의 인자는 다음과 같습니다.
- 200은 HTTP 상태 코드로, 성공적으로 요청이 처리되었음을 나타냅니다.
- {'Content-Type': 'text/html'}는 헤더 필드 객체로서, 응답 내용의 유형이 HTML임을 표시합니다.
이 코드에서 클라이언트는 서버로부터 받은 응답의 형식과 상태를 이해할 수 있게 됩니다.
이미지 파일 불러오기
const fs = require('fs');
const http = require('http');
http.createServer((request, responese) =>{
fs.readFile('./pet.jpg', (error, data)=>{
responese.writeHead(200, {'Content-Type':'image/jpeg'});
responese.end(data);
});
}).listen(5500, ()=>{
console.log('서버가 동작중입니다. http://127.0.0.1:5500');
});
- request
const http=require('http');
http.createServer((request, response)=>{
response.writeHead(200, {
'Context-Type': 'text/html',
'Set-Cookie':['name=Hong', 'age=20']
});
response.end(`<h1>${request.headers.cookie}</h1>`);
}).listen(5500, ()=>{
console.log('서버가 동작중입니다. http://127.0.0.1:5500');
});