Nodejs's mean stack development (i)----routing and controller

Source: Internet
Author: User
<span id="Label3"></p><p><p>Because of the job needs, recently learned node again, the last time to learn node is 2014, purely personal interest, after learning the introduction of no use, coupled with other projects to the End. Just pick it up this Time. Needless to say, the mean here refer to mongodb, Express, angular, and Node. Through the entire project is gradually integrated together. The biggest feature of the mean stack is not which frames or third parties are used, but the front and back are a language, javascript. In the early years I was also suspicious of node, I think this page operation of the DOM script language, can afford the backend so many modules? But doubt to know more about it before deciding to write this series of Articles.</p></p><p><p></p></p><p><p>MongoDB does Data storage, Express is a node-based backend framework, angular is the front-end framework, and node is the backend runtime Environment. The installation process and the features of node will not speak, a lot of online. The development environment is VS2013. <span style="background-color: #ffff99;">Ntvs</span>installed. Once node is installed, it is sometimes necessary to set the environment Variable. Enter NODE-V in the CMD directory if the version number is displayed, the installation is Correct.</p></p><p class="ptitle"><p class="ptitle">Starting Project</p></p><p><p>To create a new project in vs, Select Javascript-->node.js and select the Express4 app.</p></p><p><p></p></p><p><p>In order to avoid always CTRL + c, install nodemon, file updates, It will automatically restart,-g to install as a global.</p></p><pre><pre>NPM Install Nodemon-g</pre></pre><p><p>Modify the title in Index.js under the Routes folder to Readingclub. Then use CMD to cut into the project directory, input Nodemon start the Project.</p></p><p><p></p></p><p><p>Access lochost:3000 inside the browser, open successfully:</p></p><p><p></p></p><p><p>First look at the routes folder below the index.js, this is a simple route, the path of processing is "/", the Request method Get,req represents the response of the Request,res Representative.</p></p><p><p></p></p><p><p>The Render method has two parameters, "index", which represents the name of the view template to render, where the default view engine is jade, and the following {title: ' Readingclub '} is the data model passed to the VIEW. This is somewhat similar to the return View () of asp. net mvc, where the function is quite an action of the controller in asp. The view () default is the one that corresponds to the current action Name. and render must be Specified.</p></p><p><p>Res can also send a response directly back</p></p><pre><pre>Res.send (' respond with a resource ');</pre></pre><p class="ptitle"><p class="ptitle">Establish controllers</p></p><p><p>Unlike asp. NET MVC has the default routing rules, Express routing needs to be configured, it is advisable to put the Controller. But before we do, we'll modify the Directory. As below, create the App_server folder. Inside divide controllers, views and routes. The original views and routes can be moved directly in.</p></p><p><p></p></p><p><p>Create a new home.js in the Controllers folder and add three Methods: index, books, and About.</p></p><pre><pre><span style="color: #0000ff;">function</span> <span style="color: #000000;">(req, res) { res.render (</span>' index ', {title: ' index '<span style="color: #000000;"> }); <span style="background-color: #ffff99;">module.exports</span> </span> <span style="color: #0000ff;">function</span> <span style="color: #000000;">(req, res) { res.render (</span>' books ', {title: ' books '<span style="color: #000000;"></span><span style="color: #0000ff;">function</span> <span style="color: #000000;"> (req, res) { Res.render (</span>' About ', {title: ' about '<span style="color: #000000;"> );};</span></pre></pre><p class="ptitle"><p class="ptitle">Routing</p></p><p><p>similarly, Copy the Index.jade two times in the View folder and modify it to Books.jade and About.jade. Then we modify the routes under the index.js, using the Express frame comes with the router.</p></p><pre><pre><span style="color: #0000ff;">var</span> express = Require (' Express '<span style="color: #000000;">);</span> <span style="color: #0000ff;">var</span> router =<span style="color: #000000;"> express. Router ();</span> <span style="color: #0000ff;">var</span> homecontroller = Require ('.. /controllers/home '<span style="color: #000000;">); <span style="background-color: #ffff99;">Router.get (</span> </span> <span style="background-color: #ffff99;">'/'<span style="color: #000000;">, homecontroller.index); router.get (</span>'/about '<span style="color: #000000;">, homecontroller.about); router.get (</span>'/books ') </span> <span style="color: #000000;"><span style="background-color: #ffff99;">, homecontroller.books);</span></span> = router;</pre></pre><p><p>This is still not working, because we have changed the directory structure has not yet been reset in the App.js. First set up the Route:</p></p><pre><pre><span style="color: #0000ff;">var</span> routes = Require ('./app_server/routes/index '<span style="color: #000000;">); app.use (</span>'/', routes);</pre></pre><p><p>To modify the starting position of the view engine</p></p><pre><pre><span style="color: #008000;">//</span> <span style="color: #008000;">app.set (' views ', path.join (__dirname, ' views '));</span> App.set (' views ', path.join (<span style="background-color: #ffff99;">__dirname</span>, ' app_server ', ' views '));</pre></pre><p><p>__dirname represents the root directory. Then the browser accesses/books Or/about.</p></p><p><p></p></p><p><p>This separates the controller from the request, and the controller fills the model data into the corresponding View's template by routing the Controllers. This is the MVC pattern we're familiar With. we'll See router Again. Method Definition.</p></p><pre><pre>Router. METHOD (path, [callback, ...] Callback)</pre></pre><p><p>The method here refers to get,post,put and delete and so On. Because we can define:</p></p><pre><pre>Router.get ('/book/:bookid '<span style="color: #000000;">, homecontroller.detail); router.put (</span>'/book/:bookid '<span style="color: #000000;">, homecontroller.updatebook); Router.</span> <span style="color: #0000ff;">Delete</span> ('/book/:bookid ', homecontroller.deletebook);</pre></pre><p><p>Although the paths are the same, they represent different intentions, and the full restful,:bookid represents the Parameters.</p></p><p><p>also supports regular matching, which matches a ' get/commits/71dbb9c ' similar to this</p></p><pre><pre><span style="color: #0000ff;">function</span> <span style="color: #000000;">(req, res) { </span><span style="color: #0000ff;">var</span> from = req.params[0<span style="color: #000000;">]; </span> <span style="color: #0000ff;">var</span> to = req.params[1] | | ' HEAD '<span style="color: #000000;">; Res.send (</span>' commit range ' + from + ': ' + to ')<span style="color: #000000;"> ;});</span></pre></pre><p><p>If you need to do some processing for each request, you can use the all method:</p></p><pre><pre>Router.all (' * ', requireauthentication, loaduser);</pre></pre><p><p>This is equivalent to:</p></p><pre><pre>Router.all (' * '<span style="color: #000000;">, Requireauthentication) router.all (</span>' * ', loaduser);</pre></pre><p><p>Each of the routes in asp. net MVC needs to have a name set and cannot be repeated, and the match is no longer matched, and express has no such limit, and it continues to pass as long as the response is not Returned. In contrast, the router of Express is more flexible.</p></p><p><p>For more details, Please refer to the official Api:http://www.expressjs.com.cn/4x/api.html#router</p></p><p><p>Next we look at the whole app.js.</p></p><p><p>App.js</p></p><pre><span style="color: #0000ff;"><span style="color: #0000ff;">var</span></span>Express = Require (' Express '<span style="color: #000000;"><span style="color: #000000;">);</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">var</span></span>Path = require (' path '<span style="color: #000000;"><span style="color: #000000;">);</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">var</span></span>Favicon = require (' Serve-favicon ')<span style="color: #000000;"><span style="color: #000000;">);</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">var</span></span>Logger = require (' Morgan '<span style="color: #000000;"><span style="color: #000000;">);</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">var</span></span>Cookieparser = require (' cookie-parser ')<span style="color: #000000;"><span style="color: #000000;">);</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">var</span></span>Bodyparser = require (' body-parser ')<span style="color: #000000;"><span style="color: #000000;">);</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">var</span></span>Routes = Require ('./app_server/routes/index ')<span style="color: #000000;"><span style="color: #000000;">);</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">var</span></span>App =<span style="color: #000000;"><span style="color: #000000;">Express ();</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">View engine Setup</span></span>App.set (' views ', path.join (__dirname, ' app_server '), ' views '<span style="color: #000000;"><span style="color: #000000;">)); App.set (</span></span>' View engine ', ' Jade '<span style="color: #000000;"><span style="color: #000000;">);</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">uncomment after placing your favicon in/public</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">app.use (favicon (__dirname + '/public/favicon.ico '));</span></span>App.use (logger (' Dev ')<span style="color: #000000;">) <span style="color: #000000;">; app.use (bodyparser.json ()); app.use (bodyparser.urlencoded ({extended:</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">false</span></span><span style="color: #000000;"><span style="color: #000000;">}); app.use (cookieparser ()); app.use (require</span> (</span>' Stylus '). middleware (path.join (__dirname, ' public '<span style="color: #000000;">)) <span style="color: #000000;">; app.use (express.static (path.join (__dirname,</span></span>' Public '<span style="color: #000000;">)) <span style="color: #000000;">; App.use (</span></span>‘/‘<span style="color: #000000;"><span style="color: #000000;">, routes);</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">catch 404 and forward to error handler</span></span>App.use (<span style="color: #0000ff;"><span style="color: #0000ff;">function</span></span><span style="color: #000000;"><span style="color: #000000;">(req, res, Next) {</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">var</span></span>Err =<span style="color: #0000ff;"><span style="color: #0000ff;">New</span></span>Error (' not Found '<span style="color: #000000;"><span style="color: #000000;">); Err.status</span></span>= 404<span style="color: #000000;"><span style="color: #000000;">; Next (err);});</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">Error Handlers</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">Development Error Handler</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;">would <span style="color: #008000;">Print StackTrace</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">if</span></span>(app.get (' env ') = = = ' Development '<span style="color: #000000;"><span style="color: #000000;">) {app.use (</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">function</span></span><span style="color: #000000;"><span style="color: #000000;">(err, req, res, next) {res.status (err.status</span></span>|| 500<span style="color: #000000;"><span style="color: #000000;">); Res.render (</span></span>' Error '<span style="color: #000000;"><span style="color: #000000;">, {message:err.message, error:err}); });}</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">Production Error Handler</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">no stacktraces leaked to user</span></span>App.use (<span style="color: #0000ff;"><span style="color: #0000ff;">function</span></span><span style="color: #000000;"><span style="color: #000000;">(err, req, res, next) {res.status (err.status</span></span>|| 500<span style="color: #000000;"><span style="color: #000000;">); Res.render (</span></span>' Error '<span style="color: #000000;"><span style="color: #000000;">{message:err.message, error: {}}); Module.exports</span></span>= app;</pre><span class="cnblogs_code_collapse"><span class="cnblogs_code_collapse">View Code</span></span>1. Module definition:<p><p>First see a lot of require grammar.</p></p><pre><pre><span style="color: #0000ff;">var</span> express = Require (' Express '<span style="color: #000000;">);</span> <span style="color: #0000ff;">var</span> path = require (' path '<span style="color: #000000;">);</span> <span style="color: #0000ff;">var</span> favicon = require (' serve-favicon '<span style="color: #000000;">);</span> <span style="color: #0000ff;">var</span> logger = require (' Morgan '<span style="color: #000000;">);</span> <span style="color: #0000ff;">var</span> cookieparser = require (' cookie-parser '<span style="color: #000000;">);</span> <span style="color: #0000ff;">var</span> bodyparser = require (' body-parser '<span style="color: #000000;">);</span> <span style="color: #0000ff;">var</span> routes = require ('<span style="background-color: #ffff99;">./app_server/routes/index</span>');</pre></pre><p><p>Require says a module is applied, and NPM already has more than 250,000 packages. The modules that can be directly referenced are already installed in the Node_modules File. If it is a module of its own definition, such as routes will use relative path. The modules in node are divided into the following categories:</p></p> <ul> <ul> <li>Core modules, such as http,fs,path, etc.</li> <li>. or.. The starting relative path file module</li> <li>Absolute path File Module With/start</li> <li>Non-path form of a file module, such as a custom module.</li> </ul> </ul><p><p>The core module will load first, the module loaded with relative or absolute path, require will be converted to the real path, the results of the compilation will be put into the cache, so two times the load will be faster. Require can load. Js,.node.json files, and the remaining extensions will be loaded as. JS Files. The module is one by one corresponding to the file, and the module of a folder is called a package, and the package is usually a collection of modules. Require is used to get the module, while the exports object is used to define the Module.</p></p><pre><pre><span style="color: #0000ff;">function</span> <span style="color: #000000;">() {console.log (</span>' Hello. ') <span style="color: #000000;">);};</span></pre></pre><p><p>The equivalent is to define the interface to be called Externally. The route above is to encapsulate an entire object into the Module.</p></p><pre><pre>Module.exports = router;</pre></pre><p><p>Get the entire route object directly in App.js:</p></p><pre><pre><span style="color: #0000ff;">var</span> routes = Require ('./app_server/routes/index ');</pre></pre><p><p>See Module.exports Direct assignment Router a bit strange, would like to not overwrite the other modules, but in fact, in the process of compiling, node will be the content of the JavaScript file to be wrapped, equal to each file is scoped to the Isolation.</p></p>2.app.set<p><p>The routing start path and the view engine are set in App.js with the set Method.</p></p><pre><pre>App.set (' views ', path.join (__dirname, ' app_server ', ' views ')<span style="color: #000000;">);//here We have modified the path under App_server folder App.set (</span>' view Engine ', ' Jade ');//the default view engine is Jade</pre></pre><p><p>You can also set whether the route ignores casing, which is not ignored by Default.</p></p><pre><pre>App.set (' Case Sensitive Routing ',<span style="color: #0000ff;">true</span>)</pre></pre><p><p>You can also set whether the environment variable is a development environment or a production environment, and more settings can refer to the official documentation: http://www.expressjs.com.cn/4x/api.html#app.settings.table</p></p>3.app.use<p><p>The use method is used to register a series of middleware, listen to the request on the port, the middleware utilizes the tail trigger mechanism, each middleware passes the request object, the response object and the tail trigger function, and forms a processing stream through the Queue.</p></p><p><p></p></p><p><p>The simplest form of middleware:</p></p><pre><pre>App.use (<span style="color: #0000ff;">function</span> <span style="color: #000000;"> (req, res, next) { console.log (</span>' time:%d '<span style="color: #000000;">, Date.now ()); Next ();})</span></pre></pre><p><p>Look at the role of each middleware:</p></p><pre><pre>App.use (logger (' Dev '<span style="color: #000000;"></span><span style="color: #0000ff;">false</span> <span style="color: #000000;"> })),//parse form request (with Key-value key value pair), False indicates that the type of value is a string or array, True to indicate any type. App.use (cookieparser ());//parse cookieapp.use (require (</span>' stylus '). middleware (path.join (__dirname, ' public ' <span style="color: #000000;">) </span>' Public '));//static file path</pre></pre>4.error<p><p>We see that the app throws an error when the route is set and if the request is not returned and the page is not found. and continue to pass down</p></p><pre><pre>App.use ('/'<span style="color: #000000;">, routes);</span> <span style="color: #008000;">//</span> <span style="color: #008000;">catch 404 and forward to error handler</span>App.use (<span style="color: #0000ff;">function</span> <span style="color: #000000;"> (req, res, next) { </span><span style="color: #0000ff;">var</span> err =<span style="background-color: #ffff99;"><span style="color: #0000ff;">new</span> Error (' not Found '</span><span style="color: #000000;"><span style="background-color: #ffff99;">);</span> </span> = 404<span style="color: #000000;">; <span style="background-color: #ffff99;">next (err)</span>;});</span></pre></pre><p><p>and then, the error is Handled.</p></p><pre><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">Development Environment Error handling</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">the error stack is printed</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">if</span></span>(app.get (' env ') = = = ' Development '<span style="color: #000000;"><span style="color: #000000;">) {app.use (</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">function</span></span><span style="color: #000000;"><span style="color: #000000;">(err, req, res, next) {res.status (err.status</span></span>|| 500<span style="color: #000000;"><span style="color: #000000;">);//if It is not 404 it is considered an internal error res.render (</span></span>‘<span style="background-color: #ffff99;"><span style="background-color: #ffff99;">Error</span></span>‘<span style="color: #000000;"><span style="color: #000000;">, {message:err.message, error:err}); });}</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">production environment error handling</span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">no stacktraces leaked to user</span></span>App.use (<span style="color: #0000ff;"><span style="color: #0000ff;">function</span></span><span style="color: #000000;"><span style="color: #000000;">(err, req, res, next) {res.status (err.status</span></span>|| 500<span style="color: #000000;"><span style="color: #000000;">); Res.render (</span></span>' Error '<span style="color: #000000;"><span style="color: #000000;">{message:err.message, error: {}})</span> ;</span></pre><p><p>When an exception is detected, the error template is Rendered. Next look at the error template, a brief introduction to the Jade Syntax:</p></p><pre><pre><span style="color: #000000;">Extends layout //equivalent to asp. net MVC settings layoutblock content//equivalent asp. net MVC renderbody h1= message //display message< c7/>h2= error.status //display Error status pre #{error.stack}//error stack</span></pre></pre><p><p>This will handle the 404 and 500 error pages.</p></p><p><p>Summary: at this point, the entire default project has been introduced, This section through the Express framework to establish a basic MVC project, understand the basic request and response, Node's basic modules and middleware, and initially set up the route, set up a dedicated controller ; explains the relevant code in app.js; the next section focuses on models and views. today, Node's development environment has been very perfect, from 09 to now this technology has gone through 7 years, has a lot of books, the domestic Cnode community is very active. If the technology is likened to stock, java,c#,php These are undoubtedly the broad market white horse stocks, learning such a small risk of technology, do not worry about finding a job. And node is like the gem stock, you might think it's a big bubble, that the new company is just speculation, but he is growing Fast.</p></p><p><p>Source: Http://files.cnblogs.com/files/stoneniqiu/Reading.rar</p></p><p><p>Reference article:</p></p><p><p>Http://www.tuicool.com/articles/emeuie</p></p><p><p>Http://www.2cto.com/kf/201207/142885.html</p></p><p><p>Http://www.tuicool.com/articles/emeuie</p></p><p><p>Https://github.com/expressjs/body-parser</p></p><p><p>Books: "nodejs" "Getting MEAN with Mongo, Express, Angular, and Node"</p></p><p><p>Nodejs's mean stack development (i)----routing and controller</p></p></span>

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.