[서버 week2-3] Express 기본 문법 & 초기설정

SH·2022년 4월 12일
0

서버 세미나

목록 보기
5/14

yarn 패키지를 사용하였다 따라서 미리 yarn을 설치해야됨(npm install yarn -g)

기본 설정

  1. express 프로젝트를 할 폴더를 만든다
  2. 폴더 안에서 yarn --init
  3. package.json 파일 생성
  4. yarn add express, yarn add - @types/node @types/express, yarn add -D nodemon
  5. tsc --init, tsconfig.json 파일이 생성되면 설정해줌
  6. 폴더 안에 src 폴더 만들어줌. 이 안에 ts 파일로 코딩하는거임
  7. nodemon.json 파일 만들고 초기설정함 & nodemon 사용하기 위해 package.json 수정


    yarn run dev - 서버 실행 명령어, yarn run build - 프로젝트 명령어. 이걸 통해서 서버를 띄울 수 있음

코드 및 기본 문법

예제 코드

/src/index.ts

// 파일명이 index인 경우 가장 먼저 실행됨
import express, {Request, Response, NextFunction} from 'express';

const app = express(); // express에서 생상된 객체를 app에 받아옴

app.use(express.json()); // express에서 request body를 json으로 받아오겠다.

app.use('/api', require('./api')); 
// use -> 메서드 종류와 상관 없이 해당 엔드포인트로 끝나는 모든 요청. 
// localhost:8080/api -> api 폴더로 감
// localhost:8000/api -> index.ts에서 라우팅. user.ts로 감 

// 형태 - app.http 요청 메시지 
// /를 엔드포인트로 함(모두 받음)
app.get('/', (req: Request, res: Response, next: NextFunction) => {
    res.send('Hi! My name is 이름'); 
    // get 메소드의 요청이 들어왔을 때 해당 코드가 실행
}); 

// 8080 포트를 열겠다, 열리면 옆에 콜백 함수 실행
app.listen('8080', ()=> {
    console.log(`
        #############################################
            🛡️ Server listening on port: 8000 🛡️
        #############################################
    `);
});


/src/api/index.ts

import express, {Router} from 'express';

const router: Router = express.Router();

// 요청 메서드의 종류와는 상관 없이 해당 엔드포인트로 들어온 모든 요청은 user.ts 파일 실행
router.use('/user', require('./user'));

module.exports = router;

/src/api/user.ts

import express, {Request, Response, Router} from 'express';

const router: Router = express.Router(); // express의 라우팅 시스템

// GET /???/???/ 요청이 오면 아래 코드가 실행
router.get('/', (req: Request, res: Response) => {
    // 상태코드 200 던져주고 json 형태로 다음과 같은 내용을 던져줌
    return res.status(200).json({
        status: 200,
        message: '유저 조회 성공'
    });
});

module.exports = router; // 생성한 router 객체를 모듈로 반환

app.listen() 코드로 해당 번호의 포트가 열림
-> 해당 서버에 get 방식으로 localhost:8080/api/user url로 접속
-> 접속을 하면 가장 먼저 src 폴더에 있는 index.ts 파일이 실행됨
-> /src/index.ts 에서 app.use('/api', require('./api')); 코드 실행, api 폴더로 감
-> api 폴더에 있는 index.ts 파일이 가장 먼저 실행됨
-> router.use('/user', require('./user')); 코드로 ./user 파일로 이동
-> get 요청일 경우 router.get() 코드의 인자로 넣어준 콜백함수 실행됨. 여기서는 '/'로 끝나는, 즉 모든 url에 대해 아래 내용이 실행됨


기본 문법

출처: express api 문서


express()
Creates an Express application. The express() function is a top-level function exported by the express module.

app.use([path,] callback [, callback...])
Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path.

app.get(path, callback [, callback ...])
Routes HTTP GET requests to the specified path with the specified callback functions.

middleware function이란?
https://psyhm.tistory.com/8

Router (함수 아니고 오브젝트임)
A router object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router.
A router behaves like middleware itself, so you can use it as an argument to app.use() or as the argument to another router’s use() method.

router.use([path], [function, ...] function)
Uses the specified middleware function or functions, with optional mount path path, that defaults to “/”.

require() 메서드 - 외부 모듈을 가져올 때 사용
https://kyoung-jnn.tistory.com/entry/Nodejs-require-%EB%A9%94%EC%84%9C%EB%93%9C

라우팅이란?

어플리케이션의 엔드 포인트(uri의 엔드포인트)가 클라이언트 요청에 응답하는 방법

http://expressjs.com/en/guide/routing.html#routing


영상 참고

https://www.youtube.com/watch?v=c54TVVnLJDc&t=58s

profile
블로그 정리안하는 J개발자

0개의 댓글

관련 채용 정보