development

Node.js의 Connect, Express 및 "미들웨어"는 무엇입니까?

big-blog 2020. 10. 2. 22:57
반응형

Node.js의 Connect, Express 및 "미들웨어"는 무엇입니까?


JavaScript를 잘 알고 있음에도 불구하고 Node.js 생태계의이 세 가지 프로젝트가 정확히 무엇을하는지 혼란 스럽습니다 . Rails의 랙과 비슷합니까? 누군가 설명해 주시겠습니까?


[ 업데이트 : 4.0 릴리스부터 Express는 더 이상 Connect를 사용하지 않습니다. 그러나 Express는 Connect 용으로 작성된 미들웨어와 여전히 호환됩니다. 내 원래 대답은 다음과 같습니다.]

Node.js를 보는 사람들에게 분명히 공통적 인 혼란의 지점이기 때문에 이것에 대해 질문 해 주셔서 감사합니다. 이를 설명하는 최선의 방법은 다음과 같습니다.

  • Node.js 자체는 HTTP 요청에 응답하는 데 사용할 수있는 객체를 반환하는 메서드 http 모듈을 제공 createServer합니다. 해당 개체는 http.Server프로토 타입을 상속합니다 .

  • Connect 는 또한 createServer의 확장 버전을 상속하는 객체를 반환하는 메서드를 제공합니다 http.Server. Connect의 확장 기능은 주로 미들웨어를 쉽게 연결할 수 있도록합니다 . 이것이 Connect가 스스로를 "미들웨어 프레임 워크"라고 설명하는 이유이며 종종 Ruby 's Rack과 유사합니다.

  • Express 는 Connect가 http 모듈에 수행하는 작업을 Connect에 수행합니다 . createServerConnect의 Server프로토 타입 을 확장 하는 방법을 제공합니다 . 따라서 Connect의 모든 기능과 함께 뷰 렌더링 및 경로를 설명하는 편리한 DSL이 있습니다. Ruby의 Sinatra는 좋은 비유입니다.

  • 그런 다음 더 나아가 Express를 확장하는 다른 프레임 워크가 있습니다! 예를 들어 Zappa 는 CoffeeScript, 서버 측 jQuery 및 테스트에 대한 지원을 통합합니다.

다음은 "미들웨어"가 의미하는 구체적인 예입니다. 기본적으로 위의 어느 것도 정적 파일을 제공하지 않습니다. 그러나 connect.static디렉터리를 가리 키도록 구성된 (Connect와 함께 제공되는 미들웨어) 던져 넣으면 서버가 해당 디렉터리의 파일에 대한 액세스를 제공합니다. Express는 Connect의 미들웨어도 제공합니다. express.static와 동일합니다 connect.static. (둘 다 staticProvider최근까지 알려졌습니다 .)

내 인상은 대부분의 "실제"Node.js 앱이 요즘 Express로 개발되고 있다는 것입니다. 추가하는 기능은 매우 유용하며 원하는 경우 모든 하위 수준 기능이 그대로 유지됩니다.


받아 들여지는 대답은 정말 오래되었습니다 (지금은 잘못되었습니다). 다음은 현재 버전의 Connect (3.0) / Express (4.0)를 기반으로 한 정보 (소스 포함)입니다.

Node.js와 함께 제공되는 것

http / https createServer 는 단순히 콜백 (req, res)을 취하는 것입니다.

var server = http.createServer(function (request, response) {

    // respond
    response.write('hello client!');
    response.end();

});

server.listen(3000);

커넥트가 추가하는 것

미들웨어 는 기본적으로 애플리케이션 코드와 일부 하위 수준 API 사이에있는 모든 소프트웨어입니다. Connect는 내장 HTTP 서버 기능을 확장하고 플러그인 프레임 워크를 추가합니다. 플러그인은 미들웨어 역할을하므로 connect는 미들웨어 프레임 워크입니다.

그 방법은 매우 간단합니다 ( 실제로 코드는 정말 짧습니다! ). 호출하자마자 다음과 같은 var connect = require('connect'); var app = connect();기능 app얻을 수 있습니다.

  1. 요청을 처리하고 응답을 반환 할 수 있습니다. 이것은 기본적 으로이 기능을 얻기 때문입니다.
  2. 플러그인 을 관리 하는 멤버 함수 .use( source )가 있습니다 ( 이 간단한 코드 줄 때문에 여기에서 제공됨 ).

1.) 때문에 다음을 수행 할 수 있습니다.

var app = connect();

// Register with http
http.createServer(app)
    .listen(3000);

2와 결합하면 다음을 얻을 수 있습니다.

var connect = require('connect');

// Create a connect dispatcher
var app = connect()
      // register a middleware
      .use(function (req, res, next) { next(); });

// Register with http
http.createServer(app)
    .listen(3000);

Connect provides a utility function to register itself with http so that you don't need to make the call to http.createServer(app). Its called listen and the code simply creates a new http server, register's connect as the callback and forwards the arguments to http.listen. From source

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

So, you can do:

var connect = require('connect');

// Create a connect dispatcher and register with http
var app = connect()
          .listen(3000);
console.log('server running on port 3000');

It's still your good old http.createServer with a plugin framework on top.

What ExpressJS adds

ExpressJS and connect are parallel projects. Connect is just a middleware framework, with a nice use function. Express does not depend on Connect (see package.json). However it does the everything that connect does i.e:

  1. Can be registered with createServer like connect since it too is just a function that can take a req/res pair (source).
  2. A use function to register middleware.
  3. A utility listen function to register itself with http

In addition to what connect provides (which express duplicates), it has a bunch of more features. e.g.

  1. Has view engine support.
  2. Has top level verbs (get/post etc.) for its router.
  3. Has application settings support.

The middleware is shared

The use function of ExpressJS and connect is compatible and therefore the middleware is shared. Both are middleware frameworks, express just has more than a simple middleware framework.

Which one should you use?

My opinion: you are informed enough ^based on above^ to make your own choice.

  • Use http.createServer if you are creating something like connect / expressjs from scratch.
  • Use connect if you are authoring middleware, testing protocols etc. since it is a nice abstraction on top of http.createServer
  • Use ExpressJS if you are authoring websites.

Most people should just use ExpressJS.

What's wrong about the accepted answer

These might have been true as some point in time, but wrong now:

that inherits an extended version of http.Server

Wrong. It doesn't extend it and as you have seen ... uses it

Express does to Connect what Connect does to the http module

Express 4.0 doesn't even depend on connect. see the current package.json dependencies section


node.js

Node.js is a javascript motor for the server side.
In addition to all the js capabilities, it includes networking capabilities (like HTTP), and access to the file system.
This is different from client-side js where the networking tasks are monopolized by the browser, and access to the file system is forbidden for security reasons.

node.js as a web server: express

Something that runs in the server, understands HTTP and can access files sounds like a web server. But it isn't one.
To make node.js behave like a web server one has to program it: handle the incoming HTTP requests and provide the appropriate responses.
This is what Express does: it's the implementation of a web server in js.
Thus, implementing a web site is like configuring Express routes, and programming the site's specific features.

Middleware and Connect

Serving pages involves a number of tasks. Many of those tasks are well known and very common, so node's Connect module (one of the many modules available to run under node) implements those tasks.
See the current impressing offering:

  • logger request logger with custom format support
  • csrf Cross-site request forgery protection
  • compress Gzip compression middleware
  • basicAuth basic http authentication
  • bodyParser extensible request body parser
  • json application/json parser
  • urlencoded application/x-www-form-urlencoded parser
  • multipart multipart/form-data parser
  • timeout request timeouts
  • cookieParser cookie parser
  • session session management support with bundled MemoryStore
  • cookieSession cookie-based session support
  • methodOverride faux HTTP method support
  • responseTime calculates response-time and exposes via X-Response-Time
  • staticCache memory cache layer for the static() middleware
  • static streaming static file server supporting Range and more
  • directory directory listing middleware
  • vhost virtual host sub-domain mapping middleware
  • favicon efficient favicon server (with default icon)
  • limit limit the bytesize of request bodies
  • query automatic querystring parser, populating req.query
  • errorHandler flexible error handler

Connect is the framework and through it you can pick the (sub)modules you need.
The Contrib Middleware page enumerates a long list of additional middlewares.
Express itself comes with the most common Connect middlewares.

What to do?

Install node.js.
Node comes with npm, the node package manager.
The command npm install -g express will download and install express globally (check the express guide).
Running express foo in a command line (not in node) will create a ready-to-run application named foo. Change to its (newly created) directory and run it with node with the command node <appname>, then open http://localhost:3000 and see. Now you are in.


Connect offers a "higher level" APIs for common HTTP server functionality like session management, authentication, logging and more. Express is built on top of Connect with advanced (Sinatra like) functionality.


Node.js itself offers an HTTP module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.


Related information, especially if you are using NTVS for working with the Visual Studio IDE. The NTVS adds both NodeJS and Express tools, scaffolding, project templates to Visual Studio 2012, 2013.

Also, the verbiage that calls ExpressJS or Connect as a "WebServer" is incorrect. You can create a basic WebServer with or without them. A basic NodeJS program can also use the http module to handle http requests, Thus becoming a rudimentary web server.


middleware as the name suggests actually middleware is sit between middle.. middle of what? middle of request and response..how request,response,express server sit in express app in this picture you can see requests are coming from client then the express server server serves those requests.. then lets dig deeper.. actually we can divide this whole express server's whole task in to small seperate tasks like in this way. how middleware sit between request and response small chunk of server parts doing some particular task and passed request to next one.. finally doing all the tasks response has been made.. all middle ware can access request object,response object and next function of request response cycle..

this is good example for explaining middleware in express youtube video for middleware


The stupid simple answer

Connect and Express are web servers for nodejs. Unlike Apache and IIS, they can both use the same modules, referred to as "middleware".

참고URL : https://stackoverflow.com/questions/5284340/what-is-node-js-connect-express-and-middleware

반응형