Node Without Express
1. vs code editor를 연다
Node.js 내장 http 모듈을 가져와서 사용할 수 있도록 변수를 담는다
const http = require('http')
- node는 import 문법을 자동으로 지원하지 않기 때문에, require 문법을 사용하는 게 좋다.
2. http 안에 createServer라는 함수가 있다.
server를 만들어주는 함수
const http = require('http')
const server = http.creatServer((req, res)
함수의 인자가, 함수를 또 인자를 받는다.
인자
req: 클라이언트 요청
res: 줄 응답에 대한 객체 담겨 있음 (response)
const server = http.creatServer((req, res) => {
console.log('request received')
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify ({message: "Welcome to >wecode server!"}))
});
서버 요청 들어오면, 안에 있는 내부 함수가 다시 실행
res.setHeader('Content-Type', 'application/json')
요청에 대한 응답의 header를 application/json 형태로 세팅
res.end(JSON.stringify ({message: "Welcome to >wecode server!"}))
프론트엔드 개발자들이 받는 값 (함수의 인자로 넘겨주는 값이 클라이언트가 받는 응답)
- res.end함수를 통해 요청에 대한 응답 마무리.
"Welcome to >wecode server! Http server without express"
프론트엔드에게 보낼 메세지
{message: "Welcome to >wecode server! Http server without express"}))
}
key가 message, 값 value 있는 객체
이 객체를 json.stringify 함수 사용하면, json의 모양으로 변경할 수 있음
server.listen(3000,() => {
console.log('server is running on PORT 3000')
})
서버 안에 listen이라는 메소드가 있고,
인자 첫번째로는 port 를 받음.
- 메소드에 들어오는 port 번호 = 3000
express 라는 framework 없이 순수 자바스크립트로면 http server 실행하는 방법이였다.
'Wecode - Foundation 1 (부트캠프) > Node.js ( JS 구동 환경_ 서버 없이)' 카테고리의 다른 글
Node.js (0) | 2023.09.04 |
---|---|
맥북 Node.js 설치 (0) | 2023.08.30 |