11일차 Node.js 복습

Peter·2025년 4월 15일
0

Node.js CRUD 실습에 들어가면서 난이도가 갑자기 상승했다.
빌트인 함수 실습 때는 예제 보고 따라 쳐야 할 코드 양이 적었지만, 이제부터는 타이핑 양이 늘어나 그런 듯하다.
예제코드를 복습하며 어떤 의미인지 모르는 것 위주로 정리해보겠다.

app.listen()

var express = require('express')
var app = express()
app.listen(3000)

app.listen([port[, host[, backlog]]][, callback])
Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen().

If port is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).

express공식 문서에서 그대로 가져온 설명
node의 http.Server.listen()과 같다.

var express = require('express')
var https = require('https')
var http = require('http')
var app = express()

http.createServer(app).listen(80)
https.createServer(options, app).listen(443)

The app returned by express() is in fact a JavaScript Function, designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

const app = express() 이렇게 선언하고 시작하는 걸 암기하다시피 했는데 이게 알고보니 JavaScript 함수였다?
생각치도 못했는데 이래서 공식 문서를 읽어보라고 하나보다.



The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

app.listen = function () {
  var server = http.createServer(this)
  return server.listen.apply(server, arguments)
}

app.listen()의 구조가 위와 같다. Server 객체를 반환한다는데 다소 생소한 코드다.

app.use()

app.use([path,] callback [, callback...])

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.use(express.json())처럼 쓸 수도 있고, 내가 만든 함수를 넣을 수도 있다.

그렇다면 express.json()은 뭘까?

express.json()

This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

Returns middleware that only parses JSON and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body), or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.

express의 빌트인 함수. JSON 형식의 요청 본문(payload)을 자동으로 파싱해주며, 예전의 body-parser라이브러리를 기반으로 만들어졌다.

  • Content-Type 헤더가 application/json인 요청만 처리한다.
  • 요청 본문이 gzip이나 deflate로 압축되어 있어도 자동으로 압축을 풀어 분석할 수 있다.
  • JSON 형식으로 파싱한 데이터는 요청 객체의 req.body 속성에 담긴다.

참고
https://expressjs.com/ko/api.html#app.listen_path_callback

profile
개발자 지망생. 일단 하고보자

0개의 댓글