http module #0
https://nodejs.org/api/http.html
HTTP | Node.js v17.3.1 Documentation
HTTP# Source Code: lib/http.js To use the HTTP server and client one must require('http'). The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly c
nodejs.org
http module은 node.js
에서 제공해주는 모듈로써 javascript
를 이용해서 쉽게 api 서버를 구축 할 수 있게 도와준다.
최근에는 express module을 많이 사용하지만 그래도 하나씩 정리 해둘 예정
node
에서는 import 명령어를 활용해서 필요한 모듈의 내용을 불러온다.
const http = require('http');
위와 같이 불러온 후에 아래와 같이 서버를 구성한다.
const server = http.createServer((req, res) => {
res.end('Hello World');
});
createServer
함수의 콜백함수는 기본적으로 2개의 파라미터를 받는다.
첫번째는 request 줄여서 req
두번째는 response 줄여서 res
각각의 파라미터는 http모듈에서 제공하는 다양한 명령어를 사용 할 수 있다.
또한 createServer
함수내에서 여러가지 명령어를 통해서 서버를 구성 할 수 있다.
이후에는 아래와 같이 명령어를 작성하여 서버를 실행해준다.
server.listen(3000, () => {
console.log("The server is listening on port 3000 now");
});
listen
함수는 첫번째로 포트번호를 인자로 받고 두번째로 실행시의 콜백함수를 인자로 받는다.
위와 같이 작성 할 경우 3000번 포트로 http 서버가 실행된다.
그리고 실행이 완료되면 console이 출력된다.
마지막으로 아래와 같이 node를 실행 해준다.
node app.js
그럼 터미널에 콘솔 출력과 함께 localhost:3000에 들어가보면 Hello World가 출력 되어 있다.
'Node & AWS > Node' 카테고리의 다른 글
eslint, prettier, eslint-config-airbnb #2 (0) | 2022.10.09 |
---|---|
eslint, prettier, eslint-config-airbnb #1 (0) | 2022.10.09 |
socket.io (WebSocket) (0) | 2022.10.03 |
JWT (JSON Web Token) (1) | 2022.09.25 |
process.env 환경변수 (environment) (0) | 2022.09.22 |
댓글
이 글 공유하기
다른 글
-
eslint, prettier, eslint-config-airbnb #1
eslint, prettier, eslint-config-airbnb #1
2022.10.09 -
socket.io (WebSocket)
socket.io (WebSocket)
2022.10.03 -
JWT (JSON Web Token)
JWT (JSON Web Token)
2022.09.25 -
process.env 환경변수 (environment)
process.env 환경변수 (environment)
2022.09.22