Node native HTTP is not enough to meet development needs in some ways, so you need to use frameworks to speed up development
Express is a light and concise web development framework, in fact, the encapsulated HTTP. Use the tutorial to view the official website tutorial, download this third-party package before use
NPM Install Express--save
Create a portal file App.js
varExpress = require ('Express')//Primer PackagevarApp = Express ()//Create a server application equivalent to the original Http.createserver ()//when the server receives a GET request/time, executes the callback handler functionApp.Get('/', Function (req,res) {res.send ('Hello Express')//The original node's write (), end () and other APIs can still be used}) App.listen ( the, function () {Console.log ('app is running at Port.')})
The command line executes App.js and then initiates a request in the browser to get the response result of Hello Express. This is the simplest express application
Basic Routing
Refers to a mapping relationship, or a navigation, such as a GET request/when executing a corresponding function, the POST request/login when executing its corresponding function, each request has a corresponding handler function
The request method, the request path, and the request handler form a route
App.get ('/',function//get res.send (' Hello Express ')}) app.post ('/login ',function//post res.send (' Nice to meet ')})
Static Resources
Open the specified directory for outside access
// access to resources in the public directory when the request path begins with/public app.use ('/public ', express.static ('./public/')) /* If the first argument is omitted, the resource name is written directly on the access, if there is a.jpg under public, then http://127.0.0.1:3000/a.jpg can be accessed,
Http://127.0.0.1:3000/public/a.jpg is not accessible to */App.use (Express.static ('./public/'))// The first parameter does not necessarily represent the real directory name, or it can be an alias, only the request that begins with/ABC can access the resource app.use ('/abc ', express.static ('./public/') in the public directory.
Use Art-template in Express
To install art-template and express-art-template first
Express-art-template specifically integrates art_template into Express, because Express-art-template relies on art-template, so both have npm to download
NPM Install--save art-template express-art-template // Installing multiple packages at once
Configuration
// configuration using art-template template primers The first parameter means using Art-template to render the. HTML end of the file app.engine (' Art ', require (' express-art-template ' (req,res) { // express provides the render () method for response objects, which is not available by default, and the template engine is configured to use // res.render (' HTML stencil name ', {Template data}) automatically reads the file and renders the data. The second parameter can be omitted, that is, the direct output is not rendered res.render (' Index.html ' ,{title: ' user information ' , content: ' This is the content '
Express has a contract, I want developers to put all the view files in the views directory
Render () method The first parameter cannot write the path, and the template file is found by default from the views directory in the project
index.html templates and project structure
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>{{title}}</title></Head><Body> <P>{Content}}</P></Body></HTML>
Modify the default views view render Store directory
// The first parameter is not a path, it refers to the default views directory, the second parameter is path app.set (' views ', ' Custom directory ')
Middleware
Get requests pass parameters to the background through a URL stitching string
Both native HTTP and express HTTP have encapsulated the query string as a property in request , so you can get the value from the browser directly request.query
The POST request places the data in the request body, and Express does not provide the appropriate API to obtain the POST request body, but the third-party plug-in can be used
Express Middleware Body-parser is specifically to parse the POST request, so-called middleware should be to increase the functionality of the intermediate plug-in
Download the Body-parser middleware first, and be careful not to reduce the number of R
NPM Install--save body-
Then follow the tutorial configuration
var express = require (' Express ')var// lead package var app = Express () // config Body-parser, as long as this configuration is added, there will be one more Body property App.use (bodyparser.urlencoded ({extended: req) on the Request object. false })) App.use (Bodyparser.json ()) app.post ('/post ',function (req,res) { // output As Object })
Express redirects, whether send () or redirect (), Express will help us end () to stop the response
// Res.statuscode = 302
// res.setheader (' Location ', '/') // res.end () // the above three steps are node's notation, still usable, but now encapsulated, can be directly a code to implement redirection
Nodemon
Using Window's command-line tool, after modifying the code to manually restart the server, using Nodemon can be automatically restarted, it is based on node. JS developed a third-party command-line tool
// to install globally, you can execute this command in any directory, and packages installed with--global can be executed in any directory
After installation, check the version number with the nodemon-v command to see if the installation was successful, then switch node to Nodemon when executing the command.
As long as the service is started through Nodemon, it will check the file changes and then automatically restart the server, each time you modify the code save (Ctrl + s) will automatically restart the server
Nodejs Getting Started-express