express 서버 프레임워크를 사용하지 않고 개발하는 방법

express와 같이 자바스크립트 파일에서 작성

const http = require('http');

// http에서는 createServer 함수에 req, res를 파라미터로 받는 콜백함수를 생성
const app = createServer((req, res) => {
  console.log(req.url); // 서버에서 접속하는 경로를 console.log에 출력
});

app.listen(3001, () => {
  console.log('http로 가동된 서버');
});

  - 터미널에 'node app.js' 입력하여 서버 가동

   - 주소창에 'localhost:3001'을 입력하면 위에 로딩되는 것이 뜨면 서버가 열린 것

  - req.url을 console.log에 출력하도록 했으므로 처음 localhost에 들어가면 가장 첫 루트인 '/'가 console에 출력됨

  - 이후 'localhost:3001/login'을 주소창에 입력하면 /login의 경로 출력

 

  - req.url이 서버의 각 루트 경로를 가져오는 것을 이용하여 각 경로의 화면을 설정할 수 있음

// console.log(req.url); 대신 아래의 코드 입력

// 브라우저에서 한글(utf-8)로 응답해야한다고 알려주기
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});

if (req.url === '/'){
  res.end('이곳은 루트입니다.'); // express에서는 res.send()였지만 http에서는 res.end()로 사용
}
else if (req.url === '/login'){
  res.end('이곳은 로그인 화면입니다.');
}

 

  - express와 다르게 if문으로 각 경로에 대해 응답을 작성해야하므로 지저분해짐

  - 따라서 express를 쓰는 것이 훨씬 편리

'back-end > Javascript' 카테고리의 다른 글

[Node.js] Controller 분리  (0) 2022.11.22
[Node.js] 라우팅 분리  (0) 2022.11.21
[Node.js] View 분리  (0) 2022.11.20
[Node.js] 서버에 로그인 화면 적용시키기  (0) 2022.11.20
[Node.js] express 서버 띄우기  (0) 2022.11.18

+ Recent posts