-
노드js] 2 - 테스트 서버 만들기Programming 2020. 3. 2. 19:00
https://nodejs.org/dist/latest-v6.x/docs/api/synopsis.html
Usage | Node.js v6.17.1 Documentation
Usage# node [options] [v8 options] [script.js | -e "script"] [arguments] Please see the Command Line Options document for information about different options and ways to run scripts with Node.js. Example# An example of a web server written with Node.js whi
nodejs.org
서버파일 실행해보기
터미널1] node 파일이름 // 서버파일 실행 터미널2] curl -X GET 'localhost:3000/' // 클라이언트 - 요청을 보냄
테스트서버 파일 작성
// 모듈을 가져와 변수에 할당 const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; // createServer // req : 리퀘스트 객체 const server = http.createServer((req, res) => { // 콜백함수 - 사용자 요청이 들어왔을때 여기를 실행 if(req.url === '/'){ // 라우팅 추가 res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World!\n'); // 클라이언트에게 문자열을 보내줌 } else if(req.url === '/users'){ // ‘127.0.0.1:3000/users' res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('User list'); } else { res.statusCode = 404; res.end('Not Found'); } }); // listen메서드 : 서버를 요청 대기상태로 만들어준다. server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
nodejs에서 제공하는 http모듈을 사용했을때 단점
- 중복코드가 많다.
- 라우팅을 추가할수록 분기문이 늘어난다.
- ===> 이를 해결하기 위해 express 모듈을 사용!
'Programming' 카테고리의 다른 글
MVC, MVVM (0) 2020.06.26 [컨퍼런스] Apple WWDC2020 (0) 2020.06.22 [책] 읽기 좋은 코드가 좋은 코드다 - 1 (0) 2020.06.02 노드js] 1 - 기본개념 (0) 2020.03.02