"Turn" Nodejs first-order Express

Source: Internet
Author: User
Tags node server

The usual, the beginning is some of the thoughts of entertaining, think of where to write ... To today I have been working in my factory for two years, the first time since work in a business for two years, for these two years really only a full sense of accomplishment, whether it is work or life ...      Write to this sentence suddenly want to write a summary of the two years, and so on after the article was sent to organize it, Roar. That "node. js experience" seems to have occurred in the last few months, did not expect the time has been more than two years.  and see the article at the end of the sentence: "This article will only be a beginning" to make me blush to cover the face, I really did not think that the beginning of the beginning of more than two years, this let the old love why ... Well, anyway the thick skin is not two or three days, let me play the fool, I look forward to the hard truth is not.   I must be a change, a reform, a good transformation, the center of this year's small mind is the "front-end Raiders series" tossing points out, thick accumulated thin hair time to the birds. Node has to write, can't help it, too hot!     Look at the recent front-end circle, did not get a few lines of node code are embarrassed to greet others, do not toss node small platform, small tools, to the canteen are embarrassed to make a few bowls of rice, so I also shun the tide of their own work notes collation, try to write this article Nodejs series.  All right, no kidding. This article and the next several node article content, basically belong to the first order of node, slightly biased actual combat, advanced and high-level content is YY, the final catalogue and milestone next should be almost fixed. This article introduces express as the topic, extending the development of small pages with node, and then interspersed with an overview of the main API Express, the principle of routing, node module concept, by the way you will also introduce yourself using node tools and so on.   The default crossing all have JavaScript foundation, so the content that is too basic I don't waste space, GOGO. Finally, self-destruct a bar. My wife has come home to raise a fetus, so I only have time to be poor. Have time to work overtime, have time to write Bo (customer) spell accumulation ...  such as the soul of chicken soup or not to fill you, drink too much nausea:) Accidentally wrote so many random thoughts, a cool crazy drag dick fried days have wood! --------------------------------------------Gorgeous split-line--------------------------------------------
node and NPM are easy to install and don't dwell on ... There are a few basics to mention:
    1. "-G" in the Install command indicates global
    2. Express version is not the usual "-V" to view, but "-V"
    3. The commands for installing the Express project are as follows
      Express-e nodejs-product
      -E,--ejs add Ejs engine support-j,--jshtml add jshtml engine support (defaults to Jade) PS: template engine and so on temporarily do not care, but I learned to build node +express use is Ejs, so it's been used all the time
node's little base friend SupervisorEach time you modify the code, it restarts automatically.  Lazy programmers are counting on this effortless tool to live: Installation: NPM install-g SupervisorPerform: Supervisor App.js
Another Little Friends ForeverVirtual machine A close node service is off, but forever can let node service does not stop, introduced as follows, installation and execution not to elaborate, I lazy: Forever is a simple command-style Nodejs daemon, able to start, stop, restart the app app. Forever is based entirely on command-line operations, under the forever process, create a child process of node, monitor the operation of the node sub-process through monitor, once the file is updated, or the process hangs, forever will automatically restart the node server to ensure that the application is running properly. Express project DirectoryIf it is an express project structure, simply over:
    • App.js: Project entrance, anyway Express love called app.js, you can change into index.js or main.js. Equivalent to index.php, index.html in PHP projects
    • Node_modules: A dependent library for storing projects
    • Package.json: The project depends on the configuration and developer information (this to say more, or to see the document good, I will not fraught.) Take a look at the next stage, take a small section of the node module.
    • Public: Static files such as css,js,img (PS: I am actually used to call static)
    • Routes: Routing Files (important objects for learning.) Bad business, routing is the key)
    • Views: Page file (Ejs or jade template, the default is jade, I use Ejs, in the first order practiced hand most important, so you can try)
Open view file found Index.ejs is not used to, so the App.js minor changes:
    1. "App.set (' View engine ', ' Ejs ');" App.engine ('. html ', ejs.__express); App.set (' View engine ', ' html ');
    2. The Ejs variable that appears on the previous line requires the Require EJS module, adding the code "var Ejs = require (' Ejs ');"
The final app.js are as follows: Code pee:Because the first step is to get started, we still go through the use of Express and node method ha: Require () is used to load and use other modules in the current module, this method is the basis of the module, using the concept of the path is probably the line. The Ps:js file can remove the ". js" suffix exports that represents the exported object of the module, which is used to export the module's properties and public methods.   Under the project Routes folder there are Index.js and users.js (routes are in detail), all used to export objects to exports objects, such as 33 rows of Routes.index and 34 rows of user.list; PS: The code of a module will only be executed when the module is first used, and will not be initialized multiple times due to require multiple times. Express ()Represents the Create express application. A few simple lines of code can actually create an application, as follows:
     var express = require (' Express ');      var app = Express ();      App.get ('/', function (req, res) {           res.send (' Hello World ');           Console.log (' Hello World ');      App.listen (' 8808 ');
     app.listen () is the listening request on the given host and port, this and the Http.createserver of the HTTP module in node (function () {...}). Listen () effect consistent;     app.set (name, value) and App.get (name) is what you think, set () sets the value of name to Value,get () to get the set item name The value. As I app.js picture 16 line of a sentence "App.set (' Port ', Process.env.PORT | | 3000)" is to set the port of the project, you can use the http.createserver below the App.get (' Port ') to get, just I'm lazy not used to;      Learn about the App.engine () method before you look at the installation command for the Express app: "Express-e nodejs-product", where the-E and-j We have mentioned at the outset that the Ejs and jade templates are represented.       If you want to change the template suffix to ". html", you'll use the App.engine method to reset the template file extensions, such as files that you want to use the Ejs template engine to handle ". html" suffixes: app.engine ('.   HTML ', require (' Ejs '). __express);     app.engine (ext, callback) register the file of the template engine callback used to process the ext extension. Ps:__express don't have to care, it's actually a public property of the Ejs module that represents the file name extension to render.       app.use ([path], function) uses middleware function, the optional parameter path defaults to "/". The order of the middleware defined using App.use () is very important, they will be executed sequentially, and the order of use determines the priority of the middleware (often in the wrong order);       Finally introduces a useful express api:     app.render (view, [options], callback)   Render view, callback is used to process the returned rendered string.       Routing Combat:The path code should be part of the most native of the project.          Creating one or a new set of handle in Express is very simple, first look at the existing express, and in a moment we create two actual rules. The variables routes and user are all just require modules, each exports the index method and the list method, where Response.render () represents the render view, and the corresponding data is transmitted, Response.send ()     To send a response, the index and list methods are eventually executed as callback functions when the route is set. Process probably understand, we are actually engaged in a, the most easy one way, simple two steps:
    1. The first way is to add a few lines of code to the current routes/index.js or routes/test.js as follows
      Exports.test = function (req, res) {  res.send (' Test welcome. ');};

    2. In the App.js file set the route that block plus app.get ('/test ', routes.test);
The second way is two more steps, first create a new module such as Test.js file, output and then exports the corresponding method, require the module in App.js, and then add a line to set the route is complete. quickly dazzle up and integrate bootstrap:     JS Engineers use Nodejs to get started or to quickly build a site-based, so it will introduce express, then in order to make the site more dignified, integrated use of Bootstrap is the best choice, Very much like the scaffolding of its responsive layout and overall system.      PS: Because Bootstrap's JS plugin relies on Jqeury, jquery is also introduced.     The previous article has been said, static files are placed in the public folder, cut folder has helped us to the categories are divided well, images, javascripts, stylesheets.   The bootstrap.min.css files are introduced into the stylesheets directory respectively, and Jquery-1.x.x.min.js and bootstrap.min.js are placed under the JavaScripts folder.   Then we modify the view/index.html file into use, the following release I in Bootstrap demo base change index.html, we feel free to use and modify.
<! DOCTYPE html>View Code

If there is a problem with the style, check if the path to bootstrap is introduced correctly.

After starting the project feel tall on very simple, there are wood!!

  faq& Summary:Our Express project is temporary, and express does not involve any database, this thing requires a third-party node module, such as MySQL or MongoDB, follow-up I will have a chapter to introduce this piece alone.        Express is not the only web framework node in the choice, but because its document is more complete, so it is the example for everyone to introduce, its principle and implementation is not complicated after the refinement, but also hope that more JS engineers to toss out their own web framework. There are a few hours to go to the March, a month a piece but my goal, so comprehensive demo I then fill the ha.If you think this article is also the intention, please Lau the lower right corner of the recommendation. Finally, Beijing & Shanghai Friends want to change jobs, Baidu Mobile cloud sincerely incomparable look forward to "have technology, destroy the bottom line, no moral integrity, big smart, more diligent" you ... (JD and my mailbox in the top right corner of the page)References:Http://express.jsbin.cn/api.html http://www.embeddedjs.comnode's little friends supervisor and Forever don't forget, believe you'll like them:)original link: http://www.cnblogs.com/Darren_code/p/node_express.html

Go to Nodejs first-order Express

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.