Nodejs's Express use tutorial _node.js

Source: Internet
Author: User
Tags error handling http request sendfile

Express is a concise, flexible node.js Web application Development framework that provides a wide range of features to help you create Web and mobile device applications.

1.EXPRESS Organizational Structure

App Demo

|---node_modules------to install the local module.
|---Public------------to store files that users can download, such as pictures, scripts, style sheets, and so on.
|---Routes------------for storing routing files.
|---Views-------------templates for storing web pages.
|---app.js------------the application's startup script.
|---The configuration file for the Package.json------project.

2. Create Express Server

App.js file
var express = require (' Express ');
var app = Express ();
Specifies the contents of a more catalog display
app.get ('/', function (req, res) {
 res.send (' Hello World ');
};
Specifies the listening port
var server = App.listen (3000, function () {
  console.log (' Listening on port%d ', server.address (). Port );
});

Running the Nodejs application

/>node App.js

3. Middleware

Middleware (middleware) is the function that handles HTTP requests.
When an HTTP request is entered into the server, the server instance invokes the first middleware and, depending on the settings, decides whether to call the next middleware again.

The parameters of the middleware are:

. Four when---the first one is for error handling, the second requests request for the client, the third is the server response respond, and the fourth is next middleware. such as function (error, request, response, next) {}
. Three---The first client requests request, the second is the server response respond, and the third is next middleware. such as function (request, response, next) {}
. Two when---the first client requests request, and the second responds respondfunction to the server. such as function (request, response) {}

4. Using the middleware use

Use is the method of express calling middleware, which returns a function.

App.use (function (request, response) {
 Response.writehead ({"Content-type": "Text/plain"});
 Response.End ("Hello world!\n");

5. Error content Display

App.use (Express.bodyparser ());//Use the body parameter
app.use (Express.methodoverride ());//Use function to overwrite
app.use (app.router );//Use Routing
app.use (function (err, req, res, next) {
 console.error (err.stack);
 Res.send (+, ' something broke! ');
}; /error content display

6. Routing

Express routing has a variety of ways, here are some examples of commonly used:

. App.use ('/', middleware);//get/post, for path/processing
. App.get ("/", middleware); for path/processing when get in//http
. App.post ("/", middleware); for path/processing when post in//http
. App.put ("/", middleware); When put in//http, for path/processing
. App.delete ("/", middleware); for path/processing when delete in//http

7. Path wildcard character *

. * Indicates all paths

App.get ("*", function (request, response) {
 Response.End ("404!");
}); /all paths are returned 404

.: Capturing Path content

App.get ("/hello/:who", Function (req, res) {
 res.end ("Hello," + req.params.who + ".");
}); /such as "/hello/alice" URL, alice in the URL will be captured as the value of the req.params.who attribute

8. Setting environment variable Set

Set is used to specify the value of a variable.
App.set ("View Engine", "Ejs");//use Ejs as Template

9.response Object method

. REDIRECT redirect

Response.Redirect ("/hello/anime");//Redirect to/hello/anime

. send File Sendfile

Response.sendfile ("/path/to/anime.mp4");

Renders the page template render, which loads the transformed content onto the Web page.
Response.render ("index", {message: "Hello World"})//Pass the message variable to the index template with the value "Hello World" rendered as an HTML page

10.requst Object method

. Get customer IP Address: request.ip

. Get uploaded file: request.files

11. Start Script Package.json

Package.json is used to specify app information, Nodejs version number, and dependencies on other components

{
  "name": "Demo",
  "description": "My I-Express App",
  "version": "0.0.1",
  "dependencies": {
   " Express ': ' 3.x '
  }
}

12.app entrance App.js

App.js mainly includes HTTP creation, basic routing, listening port number

13. Dynamic Page Template views

Views folder, which is used to store all page templates.

App.js
app.get ('/', function (req, res) {
  res.render (' index ', {title: ' recent article}
'); Index.js This is
<%=title%>!

14. Specify a static Web page directory

App.js
App.use (express.static (' public '))//Specify a static web directory, and when the browser makes a non-HTML file request, the server ends up looking for the file in the public directory

such as: <link href= "/bootstrap/css/bootstrap.css" rel= "stylesheet", server-side to public/bootstrap/css/ Find Bootstrap.css file in directory

Well, this tutorial first to introduce to you here, follow-up will continue to give you updates, thank you all have been the cloud-Habitat community website support.

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.