yarn 패키지를 사용하였다 따라서 미리 yarn을 설치해야됨(npm install yarn -g)
/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
영상 참고