뒤끝 (Back-End)
[Node.js] 간단한 서버 열어보기
z_zen
2023. 5. 10. 20:42
728x90
const http = require("http")
require() : 모듈을 읽어오는 함수
const server = http.createServer(callback)
creatServer() : 서버 인스턴스 만드는 함수
callback : http 서버로 요청이 들어오면 해당 요청을 처리, req와 res를 인수로 받는다
log(count)
요청에 대한 로그를 남긴다, count를 1씩 증가
res.statusCode = 200
요청에 대한 상태 코드를 200으로 설정
| 200 | OK | 요청 처리 성공 |
| 301 | Moved Permanently | 요구한 데이터를 변경된 URL에서 찾음 |
| 304 | Not modified | 클라이언트의 캐시에 저장되어 있음 |
| 400 | Bad Request | 요청 실패, 클라이언트의 요청에 문제가 있음 |
| 403 | Fornidden | 접근 금지 |
| 404 | Not Found | 페이지를 찾을 수 없음 |
| 405 | Method not allowed | 요청한 메소드가 허용되어 있지 않음 |
| 408 | Request timeout | 요청 시간이 지남 |
| 500 | Internal Server Error | 서버 에러 |
| 501 | Not Implemented | 필요한 기능이 서버에 구현되어 있지 않음 |
| 502 | Bad gateway | 게이트 웨이 상태가 좋지 않음 |
| 503 | Service Unavailable | 서버가 사용 불가 상태임 |
res.setHeader("Content-Type", "text/plain")
부가 정보 설정, Content-Type을 text/plain으로 설정
Content_Type : 해당 콘텐츠가 어떤 형태의 데이터 인지 나타낸다
text/plain : 텍스트를 평문으로 해석
res.write("hello\n")
응답으로 hello\n 보내준다
setTimeout(() => {res.end("Node.js") }, 2000)
setTimeout() : 콜백 함수와 숫자를 인수로 받는다, 숫자는 밀리초단위이며, 해당 시간이 지나면 콜백 함수를 실행한다
2초후 Node.js를 응답으로 주고, http 연결을 끝내는 동작 수행
server.listen(8000)
사용할 포트 번호를 8000번으로 지정
DNS = 53, HTTP = 80, HTTPS = 442
const http = require("http");
let count = 0;
const server = http.createServer((req, res) => {
log(count);
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.write("hello\n");
// prettier-ignore
setTimeout(() => {
res.end("Node.js");
}, 2000);
});
function log(count) {
console.log((count += 1));
}
server.listen(8000, () => console.log("Hello Node.js"));
728x90