Making Server #1 (Node JS, Express, NodeMon)

0_CyberLover_0·2022년 3월 18일
0

Node.JS # 01

목록 보기
8/21
post-thumbnail

먼저 src(source) 폴더를 만들어 준다음 index.js를 넣어준다.

package.json 파일에서 Scripts에서 파일 위치를 바꿔준다. (src/index.js)

파일이름이 꼭 index.js일 필요 없다. server.js으로 바꿔 주자.

파일명을 바꾸고 나면 오류가 뜰거다. package.json파일 Scripts에서 (src/server.js) 바꿔 주자.

그 다음 이제 server.js에다가 "express" 패키지 에서 express를 import해야 한다.

import express from "express";

이렇게 입력하면 node_modules에서 express를 찾고 있다는걸 npm에서 알아서 찾아낸다.

이제 express를 쓸수 있도록 해보자.

const app = express();

express function을 사용하면 express application을 생성해주는 거다.

서버란 항상 대기 하고 있는 컴퓨터라고 생각하면 된다.

(정보를 받기 위해서 항상 주시하고 있는 컴퓨터 )

서버가 사람들이 뭔가를 요청할때 까지 기다리게 해야 한다.

app.listen()

서버에게 어떤 port를 listening할지 말해줘야 한다.

port란 컴퓨터의 문이나 창문 같은것이다.

몇몇 port들은 인터넷에 오픈되어 있다. 보통 높은 숫자의 port들은 비어 있다.

그래서 이런식으로 작성한다.

app.listen(4000, handleListening);

이제 함수를 만들어 보자.

console.log("Server listening on port 4000 🚀");

그러면 이제 console에

Server listening on port 4000 🚀 이라는 문구가 나타난다.

보통 서버를 시작했다면 localhost를 통해서 접속 할수 있다.
주소창에 localhost:4000이라고 쳐보면 된다.
Cannot GET / 이라는 문구가 떴다면 성공 한거다.

서버를 차단하고 싶다면 nodemon을 종료하면 된다. (단축키 Ctrl + c)

다시 접속을 하고 싶으면 npm run dev 좀더 괜찮게 바꾸고 싶다면

import express from "express";

const PORT = 4000;

const app = express();

const handleListening = () =>

console.log(`✅ Server listening on port http://localhost:${PORT} 🚀`);

app.listen(PORT, handleListening);
profile
꿈꾸는 개발자

0개의 댓글