키워드 : Express, 미들웨어
Express
- Node.js 환경에서의 웹 서버, 또는 API 서버 제작용 프레임워크
- Node.js HTTP 모듈과의 차이점 : 미들웨어 추가 가능, 라우터 제공
- 라우팅 :
- 메서드와 url(/lower, /upper 등..) 로 분기점을 만드는 것.
- 클라이언트 요청에 해당하는 endpoint를 따라 서버가 응답하는 방법을 결정하는 것
- 미들웨어
- 미들웨어를 사용하는 상황 :
- POST 요청 등에 포함된 body(payload)를 구조화할 때(쉽게 얻어내고자 할 때)
- 모든 요청/응답에 CORS 헤더를 붙여야 할 때
- 모든 요청에 대해 url이나 메서드를 확인할 때
- 요청 헤더에 사용자 인증 정보가 담겨있는지 확인할 때
- 미들웨어를 사용하는 상황 :
(대충 끄적여본 연습용 예시 코드)
const express = require("express");
const cors = require("cors");
const jsonParser = express.json();
const app = express();
const port = 3000;
// app.use(cors());
app.use(jsonParser);
const myLogger = function (req, res, next) {
console.log("LOGGED");
next();
};
app.use(myLogger);
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.post("/api/users", jsonParser, function (req, res) {
res.send(req.body.message.toUpperCase());
});
app.get("/products/:id", cors(), function (req, res, next) {
res.json({ msg: "This is CORS-enabled for a Single Route" });
});
//res.json : 인자는 객체 -> JSON화 -> body에 저장 -> res.send (객체 형식으로 들어감으로 여러 데이터가 들어갈 수 있음.)
//res.send : 인자는 body -> body는 chunk(buffer)로 할당.
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
Reference
http://expressjs.com/ko/api.html#express
Express 4.x - API 참조
Express 4.x API express() Creates an Express application. The express() function is a top-level function exported by the express module. var express = require('express') var app = express() Methods express.json([options]) This middleware is available in Ex
expressjs.com
https://haeguri.github.io/2018/12/30/compare-response-json-send-func/
Haeguri Devlog
공유하고 싶은 것들을 정리한 공간입니다.
haeguri.github.io
느낀점
- Node.js HTTP 모듈로 작성하는 것보다 Express가 좀 더 직관적이라고 볼 수 있다.
- API 전송 및 응답 테스트할 때는 POSTMAN이 아주 유용하다.
- 서버 연결이 제대로 되고 있는지 아직도 감이 제대로 안잡히는 듯 하다.
- 다음 세 가지를 정확히 구분할 수 있는지 더 공부해보자 :
- res.json
- res.send
- res.end
'코딩' 카테고리의 다른 글
[자료구조/알고리즘] 재귀함수 (0) | 2022.06.23 |
---|---|
모의 기술 면접 질문 리스트 (0) | 2022.06.21 |
[Web server] 기초 (0) | 2022.06.16 |
[React] 클라이언트 Ajax 요청 (0) | 2022.06.14 |
[HTTP] Web application architecture (0) | 2022.06.12 |