Today I Learned (2024.02.20) +1

다율·2024년 2월 20일

TIL

목록 보기
15/23
post-thumbnail

이미 두곳에 작성한 게 있기 때문에 이번엔 복습 겸 간략히 작성해보겠습니다!
1. https://velog.io/@dayul/Node.js-%EA%B8%B0%EC%B4%88-%EC%A0%95%EB%A6%AC
2. https://velog.io/@dayul/api-%ED%95%B4%EC%84%9D%ED%95%98%EA%B8%B0


Express와 서버

명령어

npm install 모듈 : express 설치 등 모듈 설치

node 파일이름.js : js 파일 실행
=> localhost:3000 확인하기 (브라우저에서)
ctrl + C : 서버 종료하기

npm 사이트

  • nodemon, helmet 등 많은 유용한 모듈이 있으니 꼭꼭 이용하기!

    npm에 익숙해져라..!!!
    https://www.npmjs.com/

예) 유용한 도구 : nodemon, helmet

  • 코드를 수정하고 저장을 누를때마다 서버를 자동으로 다시 켜주는 npm 모듈

app.use()

  • 미들웨어 : 요청과 응답 사이에 한번 더 체크하는 기능을 가짐
    • 사이트 -> 요청 -- (미들웨어) --> node.js 서버로 도달

코드 설명1

  • app.js 코드
const express = require('express');     // express를 사용하기 위해 node_modules에서 찾아 express 변수에 저장
const app = express();      // express 함수가 return하는 것을 app 변수에 저장

app.get("/", function(req,res){     // get 방식의 api
    res.send('Hello World');
})

app.listen(3000, function(req,res) {    // 3000번 port를 이용, 서버의 스위치 역할
    console.log("서버 실행");
})

코드 설명2

  • router폴더에 있는 mainRouter 코드
  • app.js에서 주소관련 코드만 옮김 (따로 관리)
  • module.exports로 자바스크립트 코드를 내보내고, require로 가져옴
const experess = require('express');
const router = express.Router();    // express안에서 Router() 함수를 꺼내서 변수에 저장

router.get("/", function(req,res){     // app.get => router.get으로 변경
    res.send('Hello World');
})

router.get('/about', function(req,res){ //app.get => router.get으로 변경
    res.send("About page");
})

module.exports = router;    // router 변수를 밖으로 내보냄 (app.js에서 사용하기위해)
  • 변경된app.js 코드
const express = require('express');     
const helmet = require('helmet');
const app = express();      
app.use(helmet());  

const mainRouter = require('./router/mainRouter');  // 만든 라우터 주소 불러오기
app.use('/', mainRouter);     // 미들웨어 : 기본주소에 mainRouter 설정

app.listen(3000, function(req,res) {   
    console.log("서버 실행");
})

+ .gitignore 사용해서 node_modules 제외하기

깃허브 링크

https://github.com/dayul/web-study/tree/main/chapter_2/node-study

profile
새싹 개발자 🌱

0개의 댓글