0 Foundation to build node.js, Express, Ejs, MongoDB Server and application development _node.js

Source: Internet
Author: User
Tags install mongodb mongodb mongodb server sessions install node node server sublime text

This article from the non-fish "translation" front-end developers to start a guide, from scratch to build Node.js, Express, Jade, MongoDB server, the reason to replace Jade Ejs, because I think the ejs more in line with the habits of web programmers, More specifically, it should be more in line with PHP, ASP programmers use habits. OK, no more nonsense, just start the tutorial.

Part 1th – 15 minute installation

If you're really learning from scratch, take the time to build up the environment first. It's not hard, I'm using Win8, so it looks a little different from the tutorials on Mac and Ubuntu or other *nix systems, but it's basically the same.

Step 1th – Install Node.js

It's easy to go into the Node.js official website, click on the Green Big install button, it will automatically detect your system and give you a proper download of the installation files. (If not, click the Download button to select the download you want). Run the installer, that's all. You've installed Node.js, and NPM (Node Package manager) makes it easy for you to install a variety of useful packages into node.

Step 2nd – Install Express

Now that we've got node running, we need something that allows us to actually create an available site. Here we need to install Express, which is a framework to turn node from an original application into a Web server more like the one we normally use. We need to start with express because we need it to provide the scaffolding functionality. We enter this order:

Copy Code code as follows:

C:\NODE>NPM Install-g Express



So the Express is properly installed in our node, and it is already set to global availability. You'll see a bunch of output in the command Line window, mostly HTTP 304 and get requests, which is normal. The express should have been installed and available.

Step 3rd – Create a Express project

We are ready to use Express and Ejs, but not for CSS preprocessing. We'll write some CSS in writing. We need to use EJS or other template engines to process node and express data. If you can HTML, Ejs is not difficult. Just remember that you need to focus, otherwise things can be easily wrong.

Now enter in the same command line window:

Copy Code code as follows:

C:\node>express–sessions Nodetest1



Enter, you will see such a pile of things:


Copy Code code as follows:

C:\node>express--sessions Nodetest1
Create:nodetest1
Create:nodetest1/package.json
Create:nodetest1/app.js
Create:nodetest1/routes
Create:nodetest1/routes/index.js
Create:nodetest1/routes/user.js
Create:nodetest1/views
Create:nodetest1/views/index.ejs
Create:nodetest1/public/images
Create:nodetest1/public/javascripts
Create:nodetest1/public
Create:nodetest1/public/stylesheets
Create:nodetest1/public/stylesheets/style.css

Install dependencies:
$ cd nodetest1 && NPM Install

Run the app:
$ node App

Step 4th – Edit dependencies

OK, we have some basic project structure now, but not yet. You will notice that the Express installation process creates a file called Package.json in your Nodetest1 directory and opens the file in a text editor, which should be long.

Copy Code code as follows:

{
"Name": "Application-name",
"Version": "0.0.1",
' Private ': true,
"Scripts": {
"Start": "Node App.js"
},
"Dependencies": {
"Express": "3.4.8",
"Ejs": "*"
}
}



This is a standard JSON format file that shows our application and its dependencies. We need to add a little something. For example, calls to MongoDB and monk. Change the dependencies part into this:


Copy Code code as follows:

"Dependencies": {
"Express": "3.4.8",
"Ejs": "*",
"MongoDB": "*",
"Monk": "*"
}

Step 5th – Install dependencies

Now we've defined the dependencies for the project. The * will tell NPM to "install the latest version". Back to the Command Line window, enter the Nodetest1 directory and enter:

Copy Code code as follows:

C:\NODE\NODETEST1>NPM Install



It will output a bunch of things. This is because it directly reads our modified JSON file, identifies its dependencies, and installs the necessary files. When NPM is installed, you should have a node_modules directory that contains all the dependent files required for our project.

Now we have a fully functional app and we can run it. Let's try it! Make sure your current directory is Nodetest1 directory, enter:

Copy Code code as follows:

C:\node\nodetest1>node App.js



When you enter, you will see:


Copy Code code as follows:

Express Server listening on port 3000



That's great. Open the browser, enter http://localhost:3000, you should be able to see the express of a welcome page.

Now that you've run your own node JS WebServer, with the Express engine and the Ejs HTML template engine. It's not that hard, is it?

Part 2nd-Well, let's write "Hello, world!." ,

Open your favorite text editor or other IDE, I personally like to use sublime text. Open the App.js in your Nodetest1 directory, this file is the core of your app. You should see something like this:

Copy Code code as follows:

var express = require (' Express ');
var routes = require ('./routes ');
var user = require ('./routes/user ');
var http = require (' http ');
var path = require (' path ');



This just defines a bunch of JavaScript variables and points to some packets and dependencies, node functions, and routes. Routes (routing) is a collection of models and controllers in MVC, which is responsible for forwarding requests and also contains some processing logic. Express has created all these things for us, and we are now ignoring the user route and beginning to write the topmost route (controlled by Routes\index.js).

At the end of the above file, write:

Copy Code code as follows:

var app = Express ();



This sentence is of paramount importance. It instantiates the express and assigns it to our app variable. The next step is to use this variable to configure a bunch of express parameters. Continue typing:


Copy Code code as follows:

All environments
App.set (' Port ', Process.env.PORT | | 3000);
App.set ("Views", Path.join (__dirname, ' views '));
App.set (' View engine ', ' Ejs ');
App.use (Express.favicon ());
App.use (Express.logger (' dev '));
App.use (Express.bodyparser ());
App.use (Express.methodoverride ());
App.use (App.router);
App.use (Express.static (Path.join (__dirname, ' public '));



Here set the port, looking for views of the directory, with what template engine to handle these views, and some other things. Also note the last line, which tells Express to host the static files in the public/directory as top-level directory files. For example, your picture directory is stored in the c:\node\nodetest1\public\images\, but the actual access address is http://localhost:3000/images/.

Note: You need to take this line

Copy Code code as follows:

App.use (Express.bodyparser ());



Change into


Copy Code code as follows:

App.use (express.urlencoded ());



This is to ignore some of the warning messages in the node window during the app run. The main is some express and its plug-ins may be modified in the future. If you do not make this change, you will receive a warning that a certain function is about to expire when the program is run.

Then add:

Copy Code code as follows:

Development only
if (' development ' = app.get (' env ')) {
App.use (Express.errorhandler ());
}



This way you can do some error checking during the development process.

Continue to increase:

Copy Code code as follows:

App.get ('/', routes.index);
App.get ('/users ', user.list);



This tells the route which route to use when a URI request arrives. Note that the user variable is defined earlier and is map to/routes/user.js, and we call the list function defined in this file. Here you can display a list of users.

Continue to increase:

Copy Code code as follows:

Http.createserver (APP). Listen (App.get (' Port '), function () {
Console.log (' Express server listening on port ' + app.get (' port '));
});



Finally, create an HTTP server and start it. That's almost it.

(The above content is complete in the new Express-generated template, no need to write it yourself)

Now, let's write something useful. We don't write "Hello world!" directly on our index page, we take this opportunity to learn how to use route Routing and learn how the Ejs engine works. Add a row after the App.get () section of the App.js file above:

App.get ('/helloworld ', routes.helloworld);
If at this point you press CTRL + C at the command line and then restart the app.js process and then use the browser to access Http://localhost:3000/helloworld, you will get a very exciting node error and a heap of crash hints in the command line window. This is because we have not modified the route to handle this path. Let's do this. In your editor, go to the routes directory, find the Index.js, and open it. It should look like this:

Copy Code code as follows:

/*
* Get home page.
*/

Exports.index = function (req, res) {
Res.render (' index ', {title: ' Express '});
};




Let's add a new page. I prefer to create a separate route file for each level of directory, but now we are not going to give HelloWorld a complete directory structure under the views, so we'll use the index route for the time being. At the end of this file add:


Copy Code code as follows:

Exports.helloworld = function (req, res) {
Res.render (' HelloWorld ', {title: ' Hello, world! '});
};



It will handle this URI request, but now we don't have a real page for Res.render to render, which is ejs responsible for the job. Enter your views directory, open Index.ejs, and save it as a Helloworld.ejs file. Now it should look like this:


Copy Code code as follows:

<! DOCTYPE html>
<title><%= title%></title>
<link rel= ' stylesheet ' href= '/stylesheets/style.css '/>
<body>
<p>welcome to <%= title%></p>
</body>



It should be easy to understand.


Save the file. In the Command Line window, press CTRL + C to interrupt app.js, and then enter node app.js to restart it. Tip: When you modify a ejs template file, you do not need to reboot the server. But when you change a JS file, such as App.js or a routing js file, you must restart the server to see the effect.

After the server starts, note Server opens Http://localhost:3000/helloworld, should be able to see this beautiful interface:

All right! Now we have the route to handle our template and see the effect we want. Next we'll do some model (data layer).

Part 3rd – Create a database and read data

Step 1th – Install MongoDB

Let's turn off the text editor and go back to the command line window. First use the browser, open http://mongodb.org/, download MONGO. Click on the download link in the main menu to find the right version of your system. For 64-bit win8, download the 64-bit *2008r2+ version. After downloading is a zip file, extract to C:\mongo or C:\Program Files\mongo or anywhere, this is not important. We keep the data in our Nodetest1 directory.

Step 2nd – Run Mongod and MONGO

Create a subdirectory data in our Nodetest1 directory, then enter the bin directory of your MongoDB directory in the Command Line window, and enter:

Copy Code code as follows:

Mongod–dbpath C:\node\nodetest1\data



You will see that the MONGO server is started and the first boot takes a little time because it requires some hard disk space and some other tasks to be preconfigured. When it prompts "[Initandlisten] waiting for the connections on port 27017″, it's done." There's nothing else to do, the server is already running. Now you need to open a separate command line window, enter the bin directory of the MONGO directory, and enter


Copy Code code as follows:

Mongo



You'll see some similar hints like this:


Copy Code code as follows:

C:\mongo>mongo
MongoDB Shell version:2.4.5
Connecting To:test



This time if you look at the Mongod window, you will see that a connection has been connected. We will then use this command-line client to manually process our database, but this is not necessary for our web site.

Step 3rd – Create a database

Don't worry about the hint attached to test above. It's just that when you don't specify a database, the default database is MONGO, and it doesn't even create a database named Test unless you add a single entry. Let's create a database of our own. In the MONGO Command Line window, enter:

Copy Code code as follows:

Use Nodetest1



It will not create this database unless we insert some data into it.

Step 4th – Add some data

My favorite feature of MongoDB is that it uses JSON as a data structure, which means I'm very familiar with it. If you're not familiar with JSON, read the relevant information first, which is beyond the scope of this tutorial.

We add some data to the collection. In this tutorial, we only have a simple database, username and email two fields. Our data looks like this:

Copy Code code as follows:

{
"_id": 1234,
"username": "Cwbuecheler",
"Email": "cwbuecheler@nospam.com"
}



You can create your own _id field values, but I think it's best to let MONGO do it. It creates a unique value for each record. Let's see how it works. In the Mongo window, enter:


Copy Code code as follows:

Db.usercollection.insert ({"username": "Testuser1″," email ":" Testuser1@testdomain.com "})



Important: DB is the NODETEST1 database we created above, Usercollection is our collection, the equivalent of a datasheet. Note that we do not need to create this collection in advance, and it will be created automatically the first time it is used. OK, press ENTER. If all goes well, you will see ... There's nothing. This is not very good, enter:


Copy Code code as follows:

Db.usercollection.find (). Pretty ()



If you're curious, the pretty method formats the output and adds a newline indent. It should show:


Copy Code code as follows:

{
"_id": ObjectId ("5202b481d2184d390cbf6eca"),
"username": "TestUser1",
"Email": "testuser1@testdomain.com"
}



Of course, you get objectid should be different, MONGO will automatically generate one. If you've ever used a service with a JSON interface, do you now feel like, wow, calling this on the Web should be easy! Well, you're right.

Tip: As a formal service, you should not want all the data to exist at the top level. About the MONGODB data structure of the design, see more Google it.

Now that we have a piece of data, let's add a little bit more. In the Mongo window, enter:

Copy Code code as follows:

Newstuff = [{"username": "TestUser2", "email": "testuser2@testdomain.com"}, {"username": "Testuser3", "Email": "tes Tuser3@testdomain.com "}]
Db.usercollection.insert (Newstuff);



Note that we pass more than one data to the collection through a single piece of data. How easy! Then use the Find command above and you will see these three data.

Now we're going to consolidate the Web servers and databases we built earlier.

Step 5th – Connect the MONGO to node

Now let's build a page that shows the records in the database as a nice table. This is the HTML content we are going to generate:

Copy Code code as follows:

<ul>
<li><a href= "mailto:testuser1@testdomain.com" >testuser1</a></li>
<li><a href= "mailto:testuser2@testdomain.com" >testuser2</a></li>
<li><a href= "mailto:testuser3@testdomain.com" >testuser3</a></li>
</ul>



I know it's not very scientific, but you understand. We just want to build a simple database read and write program, not to build a complete Web site. First, we add a bit of content to app.js (the heart and soul of our program) in order to MongoDB. Open C:\node\nodetest1\app.js, at the top you will see:


Copy Code code as follows:

var express = require (' Express ');
var routes = require ('./routes ');
var user = require ('./routes/user ');
var http = require (' http ');
var path = require (' path ');



Add below it:


Copy Code code as follows:

New Code
var MONGO = require (' MongoDB ');
var monk = require (' Monk ');
var db = Monk (' Localhost:27017/nodetest1 ');



These lines tell the app that we need to connect MongoDB, we use Monk to take care of the connection, our database location is localhost:27017/nodetest1. Note that 27017 is the default port for MongoDB, and if you modify the port for some reason, you should also change the record here. Now look at the bottom of the file:


Copy Code code as follows:

App.get ('/', routes.index);
App.get ('/users ', user.list);
App.get ('/helloworld ', routes.helloworld);



Add a line below:


Copy Code code as follows:

App.get ('/userlist ', routes.userlist (db));



This line tells the app that when the user accesses the/userlist path, we need to pass the DB variable to the userlist route. But we don't have userlist route yet, so let's create one now.

Step 6th – Read the data in the MONGO and display

With your editor open c:\node\nodetest1\routes\idnex.js, which has index and Hello World two route, now let's add a third:

Copy Code code as follows:

Exports.userlist = function (db) {
return function (req, res) {
var collection = Db.get (' usercollection ');
Collection.find ({},{},function (E,docs) {
Res.render (' userlist ', {
"UserList": Docs
});
});
};
};



Well, things are getting a little complicated. Here we first define a function, receive the DB variable we passed, and then call a page render like the previous two route. We tell it to read usercollection, do a lookup, and save the returned data in the docs variable. Once we read the content, we call render to render the UserList template page and pass the acquired docs variable as the userlist variable in the template engine.

Next, build our Ejs template. Open Index.ejs in the Views directory, save as Userlist.ejs, and then modify its HTML to do this:

Copy Code code as follows:

<! DOCTYPE html>
<title>USERLIST</title>
<link rel= ' stylesheet ' href= '/stylesheets/style.css '/>
<body>
<ul>
<%
for (var i in userlist) {
%>
<li><a href= "Mailto:<%=userlist[i].email%>" ><%=userlist[i].username%></a></li >
<%}%>
</ul>
</body>



Save the file and restart the node server. I hope you remember how to reboot. Open the browser, Access http://localhost:3000/userlist, you should be able to see such an interface:

Click the Submit button and you will see a "can ' t post to/adduser" error. Let's fix it.

Step 2nd – Create your database processing functions

As before, we modify the App.js, then the route file, then the Ejs template. However, there is no need for the Ejs template, because we will jump after post. Add a line after the App.js app.get ():

Copy Code code as follows:

App.post ('/adduser ', Routes.adduser (db));



Notice this is app.post, not app.get. To set the route bar. Back to Routes/index.js, create our database Insert function. This is relatively large, so I suggest you write a good note.


Copy Code code as follows:



Exports.adduser = function (db) {


return function (req, res) {

Get our form values. These rely on the "name" attributes
var userName = Req.body.username;
var useremail = Req.body.useremail;

Set our Collection
var collection = Db.get (' usercollection ');

Submit to the DB


Collection.insert ({


"Username": Username,


"Email": useremail


}, function (Err, doc) {


if (err) {


If it failed, return error


Res.send ("There is a problem adding the information to the database");


}


else {


If it worked, set the header so this address bar doesn ' t still say/adduser


Res.location ("userlist");


and forward to Success page


Res.redirect ("userlist");


}


});

}
}




Obviously in the real project you still need to do a lot of validation, such as user name and email does not allow duplication, email address must conform to a certain format rules. But for now, let's just ignore that. As you can see, when we insert the database, we let the user jump back to the UserList page where they should see the newly inserted data.

Is this the best way to do it?

Step 3rd – Connect the database, write the data

Make sure your mongod is running! Then restart your node server. Open the Http://localhost:3000/newuser in the browser. Now we fill in some content and click the Submit button. If it goes well, we should go back to the UserList page and see the new data just added.

Now that we've officially finished using Node.js,exress,ejs to read and write to the MongoDB database, we're already a cow x programmer.

Congratulations, really. If you carefully read this tutorial, and very serious study and not just copy code, you should be routes, views, read data, write data has a complete concept. This is all the knowledge you need to develop any other complete Web site! No matter what you think, I think it's pretty cool.

Part 5th – Next

From now on, you have unlimited possibilities. You can look at mongoose, another node package that handles the MongoDB database. It's bigger than monk and more functional. You can also look at stylus, a express CSS engine. You can google the node Express Mongo Tutorial and see what's next. Study hard and make progress every day.

I hope this tutorial can help, I write this because when I started to learn I really need this kind of thing, but really can't find. If you've seen it here, thank you very much!

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.