Express Node.js 프레임워크란 무엇입니까?

10380 단어 javascriptnodeexpress
Node.js의 가장 일반적인 용도 중 하나는 웹 응용 프로그램을 작성하는 것이며 이러한 응용 프로그램 중 많은 부분이 Express.js 을 사용하고 있습니다. Node.js는 웹 애플리케이션 및 서비스 구축에 탁월한 선택인데 왜 Express와 같은 서버 프레임워크가 필요한가요? Express는 Node.js 내장 도구를 사용하는 것보다 복잡성을 줄이고 애플리케이션 개발 및 유지 관리를 훨씬 쉽게 만듭니다.

이 기사는 Express에 대한 시리즈의 일부입니다. 여기에서 모든 기사를 찾을 수 있습니다 - Express Framework .

Express.js 소개

Creating a basic Hello World http server with built-in utilities in Node.js is fairly simple. The code below listens to requests on port 8000 and returns Hello World .

const http = require('http');
const port = 8000;

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('Hello World');
  res.end('\n');
});

server.listen(port, () => {
  console.log(`Server listening on port 8000`);
});

For simple servers like this, you don't need Express . In a real world scenario, I have never seen something simple as this example.

The Hello World example in Express looks like this. Maybe you can already see some simplification on this example?

const express = require('express');
const app = express();
const port = 8000;

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

Under the hood Express uses the same built-in utilities as provided from Node.js, but Express provides a set of handlers, settings, and other tools to increase the developer experience and increase the speed of creating web servers.

Express의 핵심 개념

Most web servers listen for requests that come to the server, receive http requests at an endpoint, run some code in response to the type of HTTP verb was used and respond to the request in some way. Express.js has tools to achieve all of these steps in just a few lines of code.

Express is a project of the OpenJS Foundation 자신을 Node.js를 위한 빠르고 무의미한 미니멀리스트 웹 프레임워크라고 설명합니다.

Express.js의 세 가지 큰 개념은 다음과 같습니다.
  • 라우팅
  • 미들웨어
  • 요청/응답

  • Express의 라우팅

    Routing refers to how an application’s endpoints (URIs) respond to client requests.This is typically done with the combination of the URL pattern, and the HTTP method (verb) associated.

    For example:

    • If a GET request for the url /home , send back the HTML for the homepage.
    • Or if a POST request with some payload is sent to /product , create a new product based on the data in the payload.

    A Route definition takes the following structure: app.METHOD(PATH, HANDLER)

    • app is an instance of express.
    • METHOD is an HTTP request method, in lowercase.
    • PATH is a path on the server.
    • HANDLER is the function executed when the route is matched.

    Routing is considered the basic building block of any API or web application, and the Express Framework provides flexible, unopinionated ways to write code to handle requests.

    Let's look at an example of routes that are defined for the GET method to the root of the app.

    const express = require('express');
    const app = express();
    
    // GET method route
    app.get('/', (req, res) => {
      res.send('GET request to the homepage');
    });
    

    In the above example, app is an instance of the express server, app.get is the HTTP request method and / is the URL path. The function passed in, is the handler that will run when a GET request is made to / . The req and res parameters stand for Requests and Response.

    요청 및 응답

    They are often shortened to req and res and stand for the request which was received by the server, and the response which will eventually be send back. These are based on built-in objects in Node.js, the ClientRequestServerResponse . 앞으로 전용 Express 라우팅 블로그 게시물이 있을 것입니다.

    단일 HTTP 트랜잭션은 요청 및 응답 주기로 대략적으로 설명할 수 있습니다.
  • 클라이언트가 서버에 요청을 보냅니다.
  • 서버가 요청을 수신하고 데이터를 읽습니다(요청 헤더, URL 경로, HTTP 메서드, 쿼리 매개변수, 쿠키, 데이터 또는 페이로드 등).
  • 서버가 클라이언트에 응답을 다시 보냅니다. 여기에는 상태 코드, 헤더, 콘텐츠 인코딩, 반환되는 모든 데이터가 포함됩니다.
  • 응답이 다시 전송되면 HTTP 트랜잭션이 완료됩니다.
  • reqres 개체를 보강하는 것은 Express가 기능을 향상하는 방법의 큰 부분을 차지하는 동시에 요청 및 응답이 처리되는 방식에 대한 제어를 유지하는 것입니다.

    미들웨어

    Middleware is code that executes during the request/response cycle. It is typically used to add functionality or augment the behaviour of the server. Middleware functions have access to the request object req , the response object res , and the next function in the application’s request-response cycle.

    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 in the stack.

    Let's look at an example for a middleware. We want to print a simple log message, when a request has ben received.

    The Hello-World example from before.

    const express = require('express');
    const app = express();
    
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    
    app.listen(3000);
    

    We create a middleware function myLogger , which will print LOG when a request to the app passes through it.

    const myLogger = function(req, res, next) {
      console.log('LOG');
      next();
    };
    

    To load the middleware we have to call app.use() specifying the middleware function.

    const express = require('express');
    const app = express();
    
    const myLogger = function(req, res, next) {
      console.log('LOGGED');
      next();
    };
    
    app.use(myLogger);
    
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    
    app.listen(3000);
    

    Middlewares are a flexible and powerful pattern to add logic and customize the Request/Response cycle. It enables to add more functionality to an Express server. There will also be dedicated blog post about middlewares in Express.

    지역 사회

    What really makes Express powerful is the community of developers working with it in production. Express is one of the most popular server frameworks used with Node.js. The Node.js ecosystem emphasizes using modules as building blocks for applications, and the Express community is taking full advantage of this with countless existing middlewares to add functionality.

    Express is a solid choice, when building a web application with Node.js. Though, please consider that, Express is unopinionated and best practices should be followed.

    TL;DR

    • Express is a minimal and extensible framework.
    • It provides a set of utilities for building servers and web applications.
    • The Express Framework provides flexible, unopinionated ways to write code to handle requests.
    • Middlewares are a flexible and powerful pattern to add logic and customize the Request/Response cycle.
    • Express is one of the most popular server frameworks for Node.js developers.
    • It is battle-tested in production environments, and a solid choice for web servers.

    Thanks for reading and if you have any questions , use the comment function or send me a message .

    If you want to know more about Express Express Tutorials .

    참조(그리고 큰 감사):

    HeyNode , ExpressJS , Github - Express , Node.js - HTTP

    좋은 웹페이지 즐겨찾기