JS to the end: node Learning Note 5

Source: Internet
Author: User
Tags hosting

The Connect tool set for HTTP development-middleware

After learning about node. JS's TCP API and HTTP API, node. JS Web Development is on the right track, but it's like a Java servlet that we can't use the most basic Servlet object to write a website, and we can't use the most elementary node HTTP API to write a complete website, we need a more powerful toolset, a Web suite, or even a web development framework (like Spring MVC under Java) to provide developers with a more user-friendly web development environment.

Basic task of creating a website--why middleware
    1. Standalone managed static files, such as: Html,css,js,images
    2. Handling errors and non-existent addresses
    3. Handling different types of requests

If we come up directly with the previous chapter of the HTTP module to do, we need to implement a "framework" to achieve a site's most basic task, if the use of production environment, we would like to have such a "framework"--connect toolset, it is best known as the Toolset, he away from the so-called "framework" There is still a gap.

Connect is based on the HTTP API, which is based on the node HTTP module, which makes it easy for web developers to use, and provides tools to work on repetitive tasks that allow developers to focus on the functional business of the application.

Connect is already a very basic node Web development toolset that is rarely seen in real-world development, and will later introduce a slightly higher-level express (still very basic for real-world development).

Special note: The code and connect versions in the Great node. js book are outdated, and if you use the latest version of connect you need to use the following method!

Import middleware modules such as Connect

The Connect module is not a native module of node. js and requires the introduction of external modules

Also import "Serve-static", "content-disposition" provides static file access support

Final Complete Package.json:

{  "name"  :   "Node-connect"       "version"  :   "0.0.1"       "description"  :   "Use connect to create a website"       "dependencies"  :{  "connect"  :    :   "latest"    "content-disposition"  :   "latest"  }     

Node NPM Package Search administration site: https://www.npmjs.com/

Note: In addition to connect, also imported serve-static, the package originally belongs to the Connect collection, after the official independent, "Great node. js" Using the 1.8.x version of Connect (too old) also contains the static middleware, where the 3.0.0+ version is used, you need to import this static middleware module.

These are website independent middleware (Connect/express is responsible for managing)

It is a good thing to separate the middleware of different functions from connect, which is easy to manage and maintain! (for developers to watch for updates)

npm install
Referencing the Connect module
//引入connect模块var=require("connect");//依然需要引入http模块var=require("http")//依然使用http模块创建服务器http.createServer().listen(3000);

Connect is now an HTTP middleware, and if you use the latest connect version of this article, you can't have Connect.createserver () in "terrific node. js," Because connect has removed this method!!!

Createserver to the HTTP module to do, fully embodies that connect is the characteristics of the middleware, rather than replace the http!

Still using Http.createserver () to create an HTTP server!!!

Using serve-static middleware to host static files

Node itself is not like Nginx,apache, he is not a full HTTP server, but a language parser.

With the development of the node. JS API, you can build a function like Nginx, which is responsible for providing the user static page, which requires the use of serve-static middleware

First of all, serve-static middleware originally belongs to the Connect middleware, has now been independent, it is said that in fact, connect with the connection is not big, but I still put the two in a back in the commentary.

Static file refers to: html,css, pictures, JS and so on

Create a new views directory under the project directory, storing static HTML files

New index.html:

<!DOCTYPE html> lang="en">    <meta charset="UTF-8">    <title></title><body>    hello world</body>

Index.js return static page code:

//Import HTTP Modulevarhttp= require("http");//introduction of Servestatic modulevarServestatic= require(' serve-static ')varFinalhandler= require(' Finalhandler ');varServe= servestatic(__dirname+'/views ',{' index ':[' index.html ',' index.htm ']});http.Createserver(function(req,Res{    Serve(req,Res,Finalhandler(req,RES));}).Listen( the);

What is Finalhandler?

The role is friendly processing cannot find the page to access the URL of the exception and error, if deleted, the user access illegal address will cause node to throw an exception to stop working.

Access pages outside the home page?

Views under Create a hello.html, directly behind the browser address + "/hello.html" to access this page.

Access to picture files?

How do I prompt to download a file?

varContentdisposition= require(' Content-disposition ')varFinalhandler= require(' Finalhandler ')varhttp= require(' http ')varServestatic= require(' serve-static ')varServe= servestatic(__dirname+'/files ', {  ' index ': false,  ' Setheaders ':Setheaders})//Mandatory Downloadfunction setheaders(Res,Path{  Res.SetHeader(' Content-disposition ', contentdisposition(path))} http.Createserver(function ONrequest(req,Res{  Serve(req,Res, Finalhandler(req,RES))}).Listen( the);

Create a new files directory, and the downloaded file will be placed inside.

In this way, serve-static middleware simplifies the code for developers to host static files, and we do not have to use the Fs+http method to implement the output stream file to the browser client.

Using the Connect middleware to handle different requests

In the previous back, if you want to give the user different access to the corresponding return, we need to write in the same createserver if...else if....else if...else....if ... To judge, so that the code is very redundant, and simply can not write all the situation clearly, and can not be extended, and simply can not be maintained.

Part of the code on the previous back:

    //Request for picture    if(req.Method == ' GET ' && req.URL.substr(-4)==". jpg"){        FS.Stat(__dirname+req.URL,function(Err,Stat{            if(Err|| !Stat.Isfile()){                Res.Writehead(404);                Res.End("I can't find a picture");                return;            }            Serve(__dirname+req.URL,' application/x-jpg ');        });    }Else if(req.Method=="GET" && req.URL=='/'){    //Request as HTML file        Serve(__dirname+'/form.html ',' text/html ');    }Else{        Res.Writehead(404);        Res.End("The URL is missing.");        return;    }

Next, use connect to rewrite the code: (The code is based on the Static-serve change).

//download file modulevarContentdisposition= require(' Content-disposition ')//No Finalhandler required//var Finalhandler = require (' Finalhandler ')The //http module creates an HTTP server that mustvarhttp= require(' http ')//static file hosting middlewarevarServestatic= require(' serve-static ')//connect Tool SetvarConnect= require("Connect");varApp= Connect(); app. Use(function(req,Res,Next{    //Any request will be printed! is a step that must be carried out    Console.Error('%s%s ',req.Method,req.URL)Next();});//Picture displayapp. Use("/images",function(req,Res,Next{    servestatic(__dirname+"/images") (req,Res,Next;});//download fileapp. Use("/files",function(req,Res,Next{    servestatic(__dirname+"/files",{' index ':false,' Setheaders ':Setheaders}) (req,Res,Next;});//Final processing, all next are not reachable after arriving hereapp. Use(function(req,Res,Next{    Res.Writehead(404);    Res.End(' 404 Not Found ')//No Next, this is the final method, return 404 Not Found on the line}); //force download functionfunction setheaders(Res,Path{  Res.SetHeader(' Content-disposition ', contentdisposition(path))}//Establish an HTTP serverhttp.Createserver(APP).Listen( the);

Notice that we still need the HTTP module to build the HTTP server, and then introduce the Connect module, as well as the previous serve-static and Content-disposition.

This piece of code is actually putting the previous classification request processing and this back to static file hosting powerful teamed up

If serve-static this middleware solution is static file hosting, then the Connect middleware is actually to solve the routing, request-oriented control. This way we no longer need to use handwritten if...else to determine what type of file the user has requested.

Next () function
This function plays a very important role in Connect, the function: the different kinds of requests are concatenated linearly in a row, each app.use () is actually similar to the original If...else statement that we wrote, Next is not able to handle the case, the execution of another app.use (), So as long as the return function can not be thrown to the next to do, so constantly "shake the pot", eventually no one can do there is a final function, developers need to establish such a final function, there is no next (), the last step, it must return the error to the user to see. Our final function here is a 404 error feedback.

Use () function
The first parameter can be given a requested directory, relative to the project directory that node executes, equivalent to the parameter after the first "/" behind the browser URL.

JS to the end: node Learning Note 5

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.