Home >Web Front-end >JS Tutorial >Getting started with Connect
an extensible HTTP server framework for Node.js using “plugins” known as middleware.
A middleware component is a plugin that gets a request and then does some processing, after which it might handle and end the requests or pass them on the next middleware plugin. The plugins that process the request and pass it on the next handlers are called filters, while the ones that actually handle the request are known as providers. In the first group we can find request logging plugin or authentication plugin, just to mention a few examples. As for the providers, they would mainly be part of the business logic of your application.
In this article you’ll see how to get started and use the Connect middleware framework in your Node.js applications.
$ npm initAnd then eply to the questions it’ll show (such as package name and so on). Once done, your “package.json” file should appear in the root folder with content that resembles the one below:
<span>{ </span> <span>"name": "nodejs-connect-demo", </span> <span>"version": "1.0.0", </span> <span>"description": "Demo on how to use connect framework for Node.js", </span> <span>"main": "server.js", </span> <span>"scripts": { </span> <span>"test": "echo \"Error: no test specified\" && exit 1" </span> <span>}, </span> <span>"repository": { </span> <span>"type": "git", </span> <span>"url": "https://github.com/abbassoftware/nodejs-connect-demo.git" </span> <span>}, </span> <span>"keywords": [ </span> <span>"connect" </span> <span>], </span> <span>"author": "Abbas", </span> <span>"license": "", </span> <span>"bugs": { </span> <span>"url": "https://github.com/abbassoftware/nodejs-connect-demo/issues" </span> <span>}, </span> <span>"homepage": "https://github.com/abbassoftware/nodejs-connect-demo" </span><span>}</span>
This file already contains information about the project, but it has no dependencies declared. To declare Connect as dependency, you need to add the dependency value in your “package.json” file and update it as follows:
<span>{ </span> <span>... </span> <span>"dependencies": { </span> <span>"connect": "3.x" </span> <span>}, </span> <span>... </span><span>}</span>Alternatively, you could run the command:
npm install connect --saveAt this point, we can run the following npm command to download all the dependencies (only Connect in this case):
$ npm install
Once the dependencies have been specified, we can move on creating a middleware provider which responds to all the requests using the Hello Connect response. To do that, create a “server.js” file in your Node.js project directory and add the following code:
<span>var connect = require("connect"); </span><span>var app = connect(); </span> <span>function sayHello(req<span>, res, next</span>) { </span> res<span>.setHeader('Content-Type', 'text/plain'); </span> res<span>.end('Hello Connect'); </span><span>} </span> app <span>.use(sayHello) </span> <span>.listen(3031); </span> <span>console.log("Server is listening");</span>In the above code, we first load the Connect module using Node.js require() function, and then create a server using the return value of the function. Secondly, we create a middleware component, that is nothing but a function, which takes three parameters: request , response, and next. next represents the next handler in the chain. The sayHello() function sets the header and the response text in the response object. Afterward we use this middleware component thanks to the use() function. Finally, we allow the server to listen on port 3031. Now, we can run our Connect app using the command below:
node serverIf we point our browser to localhost:3031, we should be able to see the output as follows:
In this section, we’ll delve into the request, response, and next parameters we mentioned in the previous section. The request object holds the details about the incoming request. Some of the most important information in the request objects are:
The response object holds the response that will be sent back. You can add headers and data to it depending on your application. Some important functions of the response object are:
$ npm initIn the above code we have added one more middleware component using the loggingMiddleware() function. It logs the URL and the method of the request, and parses the URL to print a possible name parameter provided. Then, it calls the next() function which will pass the request to the next handler. When we make the Connect server listen to the port, firstly we use loggingMiddleware() and then sayHello(). Now, if we start the Node.js server and run the following command:
<span>{ </span> <span>"name": "nodejs-connect-demo", </span> <span>"version": "1.0.0", </span> <span>"description": "Demo on how to use connect framework for Node.js", </span> <span>"main": "server.js", </span> <span>"scripts": { </span> <span>"test": "echo \"Error: no test specified\" && exit 1" </span> <span>}, </span> <span>"repository": { </span> <span>"type": "git", </span> <span>"url": "https://github.com/abbassoftware/nodejs-connect-demo.git" </span> <span>}, </span> <span>"keywords": [ </span> <span>"connect" </span> <span>], </span> <span>"author": "Abbas", </span> <span>"license": "", </span> <span>"bugs": { </span> <span>"url": "https://github.com/abbassoftware/nodejs-connect-demo/issues" </span> <span>}, </span> <span>"homepage": "https://github.com/abbassoftware/nodejs-connect-demo" </span><span>}</span>
we’ll see the following messages:
The next thing to do is to add an authentication to the admin section of our website using the Basic access authentication of HTTP. To do that, we have to explore how can we run a handler just for the admin section of our server. Connect’s use() function can take the first parameter as what should be the path in request.url for the handler to get invoked. So, if we want the authentication handler exclusively for the admin section, we need to update the “server.js” file as follows:
<span>{ </span> <span>... </span> <span>"dependencies": { </span> <span>"connect": "3.x" </span> <span>}, </span> <span>... </span><span>}</span>
Then we need to create a “authDetails.json” file in the same directory of “server.js” with the following content:
$ npm initIn the above code we load a JSON file called “authDetails.json” (the one just created) which will include a JSON object containing the username and password lists of the authorized users. Then we add one more Connect handler called authenticateAdmin used only for the admin section of the website. The previously mentioned handler checks the authorization header and then decodes the username/password pair, and checks it against the JSON file contents for authorization. In case the request is not authorized, an unauthorized response with response code 401 is sent to the client. With this update, if we make requests to the admin section of the site, the output will be the following:
Connect is a middleware framework for Node.js. It is a simple, flexible, and powerful tool that provides a collection of high-level plugins known as middleware. These middleware components perform various tasks such as logging, serving static files, and managing sessions. Connect essentially acts as a pipeline that processes HTTP requests and responses. It allows developers to add additional functionality to their server by plugging in different middleware components.
While both Connect and Express.js are middleware frameworks for Node.js, Express.js is built on top of Connect. This means that Express.js includes all the features of Connect, plus additional features. Express.js provides a more robust feature set for web and mobile applications, including template engines, simplified multiple routing, and a middleware interface.
To install Connect, you need to have Node.js and npm (Node Package Manager) installed on your system. Once you have these, you can install Connect by running the following command in your terminal: npm install connect.
Middleware in Connect is used by calling the use() method on a Connect application. The use() method takes a middleware function as an argument. This middleware function is then added to Connect’s stack of middleware and will be executed in the order it was added whenever a request is made to the server.
Yes, you can create your own middleware in Connect. A middleware is simply a function that has access to the request object, the response object, and the next middleware function in the application’s request-response cycle. This function can perform any operations on the request and response objects, and then call the next middleware function in the stack.
The next() function is a function in the Connect middleware that, when called, passes control to the next middleware function in the stack. If a middleware function does not call next() within it, the request-response cycle will be halted. It will not proceed to any other middleware or route handlers.
Connect provides a built-in middleware function for error handling. This middleware function takes four arguments instead of the usual three: (err, req, res, next). When you call the next() function with an error argument, Connect will skip all remaining middleware in the stack and proceed to this error handling middleware.
Yes, Connect is designed to work seamlessly with most Node.js web frameworks. In fact, many popular frameworks like Express.js are built on top of Connect. This means you can use Connect middleware within these frameworks.
Connect provides a built-in middleware function for serving static files. You can use this middleware function to serve files from a specified directory. For example, to serve static files from a directory named ‘public’, you would use the following code: app.use(connect.static('public')).
As of the time of writing, Connect is not actively maintained and updated. The last update was made several years ago. However, it is still widely used and its functionality is stable. For a more actively maintained middleware framework, you might consider using Express.js, which is built on top of Connect and includes additional features.
The above is the detailed content of Getting started with Connect. For more information, please follow other related articles on the PHP Chinese website!