recently used Nodejs and Express tried to set up a website, feel the speed is quite fast, summed up, good memory than rotten pen.
Node installation can be directly to the official website to download the latest version, installation is good.
After node is installed, we install it in turn, where G indicates a global installation, and the advantage is that it can be entered directly from the command line. -V You can view the version of the corresponding wheel, but express View version command to use-V.
NPM Install
NPM Uninstall
-express Installation
Because version four is used, enter the following statement for installation:
NPM Install-g Express
-supervisor-Automatically restarts each time the code is modified. Lazy programmers are counting on this saving tool to live:
NPM install-g Supervisor
You can then use Express to create the project .
First enter the directory where you want to build the project, and then enter the command below
Express-e Nodejs-project
Here are some simple commands for Express:-h,–help output usage information-v,–version output The version Number-e,–ejs add Ejs engine supp ORT (Defaults-j–jade)
–hbs Add handlebars engine Support-h,–hogan add hogan.js engine Support-
You can see that the directory automatically set up the appropriate folder, but this time has not been completed OH. You need to continue typing:
NPM Install
It automatically installs the packages according to the profile Package.json and puts them under the Node_modules folder.
At this point, you can start the service and enter at the command line:
node./bin/www/
Or
Supervisor./bin/www/
Then open in the browser to see the long absence of hello.
The default port is 3000.
Next, let's say the internal code:
EXPRESS4 changed the directory structure
-Bin directory: There is a www file, and this is the start file, so you can understand our startup statement.
-Node_modules: Storage of the project's dependent library;
-Package.json: The project relies on configuration and developer information, you can see the document to understand the detailed information;
-Public: Static files such as css,js,img;
-Routes: Routing files (this is the focus of siege);
-Views: Page file (Ejs or jade template, default is Jade);
To enable express to identify the HTML document I have been accustomed to, I have built a schema based on the Ejs template here. The App.set (' View engine ', ' Ejs ') is changed to App.engine ('. html ', ejs.__express); App.set (' View engine ', ' html ');
Code in App.js:
Create a project instance var app = Express ();
Define log and Output level App.use (Logger (' dev '));
Define Icon App.use (favicon (__dirname + '/public/favicon.ico '));
Define log and Output level App.use (Logger (' dev '));
Defines the data parser App.use (Bodyparser.json ());
App.use (bodyparser.urlencoded ({extended:false}));
Defines the cookie parser App.use (Cookieparser ()); Define a static file directory//view engine The location of the setup definition paging file __dirname is a global variable in Node.js that represents the path to the current execution file App.set (' Views ', Path.join (__dirname, '
Views/pages ')); Express.static () is the processing of static requests, the public file is set, all files in public will be returned as a static data file (such as styles, scripts, picture footage, etc.) App.use (express.static (
Path.join (__dirname, ' bower_components '));
Load route control var routes = require ('./routes/index ');//route var users = require ('./routes/users ');
Indicates that when users use/access, call routes, that is, the routes directory under the Index.js file, where the. js suffix omitted, with/users access, routes directory Users.js file App.use ('/', routes);
App.use ('/users ', users);
404 Error Handling App.use (function (req, res, next) {var err = new error (' Not Found ');
Err.status = 404;
Next (ERR);
}); Development environment, 500 error handling and error stack trace if (app.get (' env ') = = ' development ') {App.use (function (err, req, res, next) {Res.status (Err.status | | 500);
Res.render (' error ', {message:err.message, error:err});
});
}//Production environment, 500 error handling App.use (function (err, req, res, next) {Res.status (Err.status | | 500);
Res.render (' error ', {message:err.message, error: {}}); });
Bin/www file
#!/usr/bin/env node/** * Dependent loading/var app = require ('.
/app ');
var debug = require (' Debug ') (' nodejs-demo:server ');
var http = require (' http '); /** * Define boot port/var port = normalizeport (Process.env.PORT | |
' 3000 ');
App.set (' Port ', port);
/** * Create HTTP Server instance */var server = Http.createserver (APP);
/** * Start NETWORK SERVICE listening Port * * Server.listen (port);
Server.on (' Error ', onError);
Server.on (' Listening ', onlistening);
/** * Port Standardization Function/function Normalizeport (val) {var port = parseint (val, 10);
if (isNaN (port)) {return val;
} if (port >= 0) {return port;
return false;
}/** * HTTP exception event handler/function OnError (Error) {if (Error.syscall!== ' listen ') {throw error; var bind = typeof Port = = ' String '?
' Pipe ' + port: ' Port ' + port/Handle specific listen errors with friendly messages switch (Error.code) {
Case ' eacces ': console.error (bind + ' requires elevated privileges ');
Process.exit (1);
Break Case ' EADdrinuse ': console.error (bind + ' is already in use ');
Process.exit (1);
Break
Default:throw error;
}/** * Event binding function */function onlistening () {var addr = server.address (); var bind = typeof addr = = ' String '?
' Pipe ' + addr: ' Port ' + addr.port;
Debug (' Listening on ' + bind); }
Code in Rotes/index.js:
/* Get home page. *
//Router.get indicates that the response function is processed by a GET request//, two parameters are request, response
// Res.render indicates that the template engine is invoked to parse the templates of the name index, passing and passing in the title object as the parameter
router.get ('/', function (req, res, next) {
Res.render (' Index ', {title: ' Home '}
]; Explanation: If the URL of the GET request is the current path, the corresponding function in the route index entry is processed
app.get ('/', routes.index);
Some of these methods explain: App.set (name, value) and App.get (name) are what you want, set () to set the value of name to Value,get () to get the value of the set item name