Node.js/일반
node.js의 http 모듈 기본 사용법
Socratone
2020. 4. 18. 12:42
const http = require('http');
// 이벤트 이미터와 비슷하게 요청이 있을 때마다 호출 된다.
const server = http.createServer((req, res) => {
if(req.url === '/') { // http://localhost:3000/
res.write('환영합니다.');
res.end();
}
if(req.url === '/get') { // http://localhost:3000/get
res.write(JSON.stringify([1, 2, 3])); // [1, 2, 3]이라는 데이터를 string으로 변환해서 보낸다.
res.end();
}
});
server.listen(3000);
console.log('서버가 가동 중입니다.');
response.writeHead
특정한 헤더를 보내려면 res.write와 res.end가 나오기 전에
다음과 같이 입력할 수 있다.
res.writeHead(200, { // status code like 404
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain'
});
참고:
HTTP Module in Node.js