JS to the end: node Learning 6

Source: Internet
Author: User
Tags sendfile what php

Start the Real node Web development--express Framework

Why is it that the real start of web development is now?

First of all, any enterprise will not use the native HTTP protocol API to develop a complete Web site, unless they first develop a framework, and then our previous so-called http,connect all just open an HTTP server, at most only a tool set (middleware), Finally, using a framework like express allows us to focus on the functional business!

Productivity is thus embodied!

Introducing Express

In the previous chapter, even though we can already use connect to handle the user's various requests, but still need us to pay attention to the routing, File judgment, and connect,serve-static just played a pure intermediate role, and pieced together to assemble a seemingly good site, These do not directly enhance the HTTP API.

You can see that we're still using it require("http").createServer()" to create the HTTP service

Package.json

{    "name":"test-express",    "version":"0.0.1",    "description":"an express example",    "dependencies":{        "express":"latest",        "jade":"latest"    }}
npm install

Express is enhanced directly on HTTP, encapsulating the HTTP API, and we no longer have to worry about the HTTP API

Express Create an HTTP server
var=require("express");var=express();app.get(‘/‘,function(req,res){    res.send("hello world");});app.listen(3000);

You can see that the Express module exposes the Express method itself, returning an object whose get method has solved the problem of path handling. This is a very simple example page that has made me feel that he will make web development very simple.

Express managed static files

Using the Express framework express.static to make changes to the serve-static managed static files in the previous one, it must be explained that Express.static is the only middleware built into express. is based on serve-static and is responsible for static resources within the managed Express application. (website description)

Create a new public directory dedicated to static files: Css,js,images and other resource files can be

app.use(express.static(‘public‘));

Only one line of code is needed to test the effect

Express View business Separation--template rendering engine jade

In the beginning to develop the web that will, I have been unable to understand what PHP smarty, after the development of Java EE, slowly familiar with a noun "template engine", because PHP itself can be embedded HTML so, it is easy for beginners to ignore the concept of this template engine, and later, When developing Java, we need to be exposed to the template engine when we want to separate the front-end (HTML) back-end (Java), the main role:

Enter a variable or logical language in the specified format in a plain HTML file, replace the variable tag with the corresponding value before sending it to the client browser via HTTP, and program the logical language to eventually generate a pure HTML file stream to send to the client.

Popular words: The template engine like a processing mold, the non-pure HTML (with template code) loaded, generate new, perfect pure HTML code, so we do not need to embed in the HTML back-end statements to dynamically modify the page, which enables the separation of logic and view (template engine is one of the core content of Dynamic Web site)

Give me a chestnut and use the Jade template engine! (Requires an external module, the previous Package.json has been added)

First template storage location, New: Views Directory-New Index.jade file

Front Index.jade

doctype   html      head          title= pageTitle          script(type=‘text/javascript‘).              function showCityEx(city)              {                  return city + " & " + city;              }                body          h1 #{h1}                table(border=1)              tr                  th hello                  th world,citys.count=#{cscores.length + 3}                  th count              for city,index in citys                  tr                      td= index                      td welcome to #{city}(#{city.substr(0,4)})                      td= cscores[index]          div over!  

Back end: Index.js

varExpress= require("Express");varApp= Express();varCity_names=[' Wuhan ',      ' Tianjin ',      ' Beijing ',      ' Shanghai '];varCity_scores=[' A ',      ' a ',      ' A ',      ' a '];app. Use(Express.Static(' Public '));app.Set("View Engine","Jade");app.Set("views",__dirname+"/views");app.Get('/',function(req,Res{    Res.Render("Index",{Citys:City_names,Cscores:City_scores});});app.Listen( the);

Explain

Learn Express first ignore those jade template code, if you need to know, refer to the Jade official website api:http://jade-lang.com/

Focus on the Nodejs code, the App.get method does not change, the parameter URL is bound to the parameter callback function.

Res invokes render, which is the template engine rendering method, which indicates that a rendered HTML is output to the client

    1. Configuration one: Use App.set to configure Express to set the view engine to Jade
    2. Configuration two: The template storage location is configured as: Views directory, we put the jade file inside, and then automatically read
    3. Render parameter one: file name with no suffix
    4. Render parameter two: A variable that needs to be replaced in the jade template
    5. Render also has a callback function that handles the generated HTML, which can be written like this:
res.render("index",function(err,html){    //继续处理html,比如打印到控制台console.log(html);});

The basic use of the template engine is nothing more than: Set the template type, set the template directory, render out!

The Jade template language itself deserves to be taken out of our own learning!

Express Request and response

The entire HTTP development revolves around request (user request) and Response (response request) in development.

Express has encapsulated HTTP req and RES objects for easy development.

To document some common object methods:

Request

If you print the Req object directly you will see a mess of things that don't mean anything.

Print these things for a look at the following:

Params object

app.get(‘/user/:name‘,function(req,res){    console.log(req.params.name);})

Address field input: Http://localhost:3000/user/devil

Terminal display:

Query Object

app.get(‘/user‘,function(req,res){    console.log(req.query.name);});

Address field input: Http://localhost:3000/user?name=devil

Terminal display: Ditto!

Response

Download ()

app.get(‘/getimg‘,function(req,res){    res.download(__dirname+"/public/images/xq.jpg");});

Used to download files and force users to download the file after use

JSON () and JSONP ()

app.get(‘/json‘,function(req,res){    res.json({name:"devil",sex:"男",body:"strong"});});

Forces the conversion of a JS object to a JSON data format sent to the client, which supports JSONP, the same effect.

Redirect ()

app.get(‘/baidu‘,function(req,res){    res.redirect(‘http://www.baidu.com‘);});

Redirect to another page

Send ()

app.get(‘/send‘,function(req,res){    res.send({some:‘json‘});});

Send is a very common method of express, the function is huge, the advantage is the automatic conversion format, input digital send status code, input string to return the client string, input JS object return JSON object, he can make a good judgment on the parameter data type, better than the above JSON () method.

SendFile ()

app.get(‘/send‘,function(req,res){    res.sendFile("E:\\视频\\电影\\v字仇杀队.mp4");});

This is interesting, is to send files, but does not allow users to download, should be a binary stream of the way to send files, theoretically also need browser support, test results:

If it is a picture file, the picture is displayed.

JS to the end: node Learning 6

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.