-
[강의 정리] Node.js로 간단한 API 구현 및 정적 파일 제공해보기 by 동빈나공부 기록/JavaScript 2023. 2. 8. 00:16728x90
* Reference Video: https://www.youtube.com/watch?v=BqMJ7w4SppU
목표: API 개발자 입장에서 API를 구현하고 swagger ui를 붙여보자.
npm init 초기화 -> 이전 강의에서는 초기화 안했는데 왜 하는거지?.
https://expressjs.com/en/guide/routing.html
1. nodejs로 API 서버 구축. 3000포트에서 열리도록
2. adder라는 이름의 API를 명세 (파라미터로 one, two에 전달되는 값을 더해서 반환하는 API)
3. 정적파일 제공 (test.html)
var express = require('express'); var app = express(); //API 문서화를 위하여 누구나 볼 수 있는 형태로 제공하기 위해 정적 파일 제공하기 위한 static() 호출 // public 폴더에 저장된 파일만 제공 app.use(express.static('public')); // 기본 경로에 접속했을 때 다음 응답 반환 app.get('/', function(req,res){ res.send('Hello World!'); }); // adder라는 이름의 API를 명세 app.get('/adder', (req, res) =>{ let one = req.query.one; let two = req.query.two; let result = Number(one) + Number(two); res.send(String(result)); }); // 포트명과 콜백함수 정의. 3000 포트로 정상적으로 서버가 띄워주면 로그 출력 app.listen(3000, () => { console.log('Start listening on port 3000'); });
강의해서 API 문서화를 위하여 누구나 볼 수 있는 형태로 제공하기 위하여 app.use()..를 추가한다고 했는데 무엇인지 알아보자.
app.use()는 미들웨어와 관련이 있는데 공식 문서를 보자면,
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=pjok1122&logNo=221545195520
2. 정적 파일 제공하기
app.use(express.static('public'));
express 변수에는 stastic이라는 메서드가 포함되어있습니다. 이 메서드를 미들웨어로서 로드해줍니다. static의 인자로 전달되는 'public'은 디렉터리의 이름입니다. 따라서 'public' 이라는 디렉터리 밑에 있는 데이터들은 웹브라우저의 요청에 따라 서비스를 제공해줄 수 있습니다.
가령, 사용자가 127.0.0.1:3000/images/cat.jpg 로 접근한다면, 해당 파일을 public/images/cat.jpg에 존재하는지 검색하게 됩니다.
이와 같은 방법은 public에 저장된 파일만을 제공한다는 점에서도 보안적인 이점이 있습니다.코드를 구현하고 public 폴더를 만들게 되는데, 이 폴더는 외부에서 접근이 가능하다. 즉, 사용자들이 API 문서를 보기 위해 접근할 수 있는 공간을 별도로 분리해두는 것이다.
짧은 강의지만 중요한 개념들을 배운 유익한 강의였다.
참고
- https://velog.io/@nemo/node-middleware-next
Next
- https://www.youtube.com/watch?v=FYS7Zt2LPis
'공부 기록 > JavaScript' 카테고리의 다른 글
바닐라JS 챌린지 시작 (3/20~) (0) 2023.03.20 [강의 정리] Node.js웹 서버에 Swagger UI 입혀보기 by 동빈나 (0) 2023.02.09 [강의 정리] Node.js에서 API 서버 만들기 by 개발자의 품격 (0) 2023.02.06 [강의 정리] 한시간만에 끝내는 Node.js by 개발자의 품격 (0) 2023.02.05 [강의 정리] 자바스크립트의 역사와 현재 그리고 미래 by 드림코더 (0) 2023.02.03