Nodejs express tutorial _ node. js-js tutorial

Source: Internet
Author: User
Tags sendfile
Express is a simple and flexible node. jsWeb application development framework, which provides a series of powerful features to help you create a variety of Web and mobile device applications. This article introduces the nodejs express tutorials, if you are interested, Express is a simple and flexible node. the js Web application development framework provides a series of powerful features to help you create various Web and mobile device applications.

1. express Organization Structure

App demo

| --- Node_modules ------ install the local module.
| --- Public ------------ used to store files that can be downloaded by users, such as slice, script, and style sheet.
| --- Routes ---------- used to store route files.
| --- Views ------------- templates used to store web pages.
| --- App. js ------------ STARTUP script of the application.
| --- Package. json ------ configuration file of the project.

2. Create an express Server

// App. js file var express = require ('express '); var app = express (); // specify the content displayed in the app directory. 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 );});

Run the nodejs Application

/> Node app. js

3. Middleware

Middleware (middleware) is a function used to process HTTP requests.
When an HTTP request is sent to the server, the server instance calls the first middleware. Then, based on the settings, the server instance determines whether to call the next middleware.

Middleware parameters:

. Four times --- the first is error processing, the second is the customer request, the third is the server response respond, and the fourth is the next middleware. for example, function (error, request, response, next ){}
. Three times --- the first customer request, the second is the server response respond, and the third is the next middleware. For example, function (request, response, next ){}
. Two times --- the first client request, and the second server response respondfunction. For example, function (request, response ){}

4. use Middleware

Use is the method used by express to call the middleware. It returns a function.

app.use(function(request, response) { response.writeHead(200, { "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 the function to overwrite the app. use (app. router); // use the routing app. use (function (err, req, res, next) {console. error (err. stack); res. send (500, 'something broke! ') ;}); // Display Error content

6. Routing

There are multiple express routing methods. Here are several common examples:

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

7. Path wildcard *

. * Indicates all paths

App. get ("*", function (request, response) {response. end ("404! ") ;}); // All paths return 404

.: Capture path content

App. get ("/hello/: who", function (req, res) {res. end ("Hello," + req. params. who + ". ");}); // For example,"/hello/alice ", alice in the URL will be captured as req. params. who Attribute Value

8. set the environment variable set

Set is used to specify the value of a variable.
App. set ("view engine", "ejs"); // use ejs as a template

9. response object Method

. Redirect

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

. Send File sendFile

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

. Render the webpage template render, that is, load the transformed content to the webpage.
Response. render ("index", {message: "Hello World"}); // pass the message variable to the index template and the value is "Hello World" to render it into an HTML webpage.

10. requst object Method

. Get customer ip Address: request. ip

. Get the uploaded file: request. files

11. Start the script package. json

Package. json is used to specify the dependencies between app information, nodejs version numbers, and other components.

{  "name": "demo",  "description": "My First Express App",  "version": "0.0.1",  "dependencies": {   "express": "3.x"  }}

12. app. js

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

13. Dynamic Webpage template views

Views folder, used to store all webpage templates.

// App. jsapp. get ('/', function (req, res) {res. render ('index', {title: "recent article"}) ;}); // index. jsthis is <% = title %>!

14. Specify the static webpage directory

// App. js
App. use (express. static ('public'); // specifies the static Web page Directory. When the browser sends a non-HTML file request, the server searches for the file in the public directory.

For example: On the server side, search for the bootstrap.css file in the public/bootstrap/css/directory.

Now, this tutorial will introduce you here, and we will continue to update you later. Thank you for your continued support for the script home website .!

Related Article

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.