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 toreq
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 ClientRequest 및 ServerResponse . 앞으로 전용 Express 라우팅 블로그 게시물이 있을 것입니다.단일 HTTP 트랜잭션은 요청 및 응답 주기로 대략적으로 설명할 수 있습니다.
req
및 res
개체를 보강하는 것은 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
Reference
이 문제에 관하여(Express Node.js 프레임워크란 무엇입니까?), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/mariokandut/what-is-the-express-nodejs-framework-338d텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)