#3.0 my first nodeJS server

이원규·2022년 5월 31일
0

Itube

목록 보기
5/46
서버 만들기 전 수정
  1. src라는 폴더를 만든다.(이 폴더에는 코드와 로직 등을 넣을 것임.)

  2. index.js 파일 이름을 server.js로 변경

  3. server.js를 src폴더에 넣는다.

  4. package.json 파일에서

"scripts": {
    "dev": "nodemon --exec babel-node src/server.js"
  },

이처럼 scripts에서 server.js파일의 이름과 경로를 바꾸어준다.
터미널에서 npm run dev를 입력하여 다시 nodemon을 실행함

server 만들기 (server.js에서)
  1. 코드작성
import express from "express";// 혹은 "node_modules/express"

const PORT = 4000;

const app = express(); //express application(server:24시간 내내 온라인에 연결된 켜져있는 컴퓨터)생성 -> 이제 app이 request(누군가 서버에 연결할 때 이를 허가하도록 요청하는것.)를 listen할 수 있도록 해줘야함.

const handleListening = () => console.log(`Server listening on port http://localhost:${PORT}`);


app.listen(PORT, handleListening);//port:서버에 들어갈 수 있는 문이나 창문 같은 거.(숫자는 상관 없음, 보통 높은 숫자가 비어있음) callback: 서버가 시작될 때 작동하는 함수.![](https://velog.velcdn.com/images/wklee0607_/post/3f1972e4-2913-460c-8713-7890eb7ab387/image.jpeg)

-서버에 접속하는 법: 크롬에가서 http://localhost:4000/ 입력(localhost:port번호)
-서버와 nodemon접속 끊기(끊으면 listen을 못함) 컨트롤+C / npm run dev하면 다시 서버 연결

profile
github: https://github.com/WKlee0607

0개의 댓글