In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to develop a bookstore with NodeJS+MongoDB+AngularJS+Bootstrap". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to develop a bookstore with NodeJS+MongoDB+AngularJS+Bootstrap.
Example name: Tiangou Bookstore
Function: complete the book management function of the separation of the front and back end, and summarize the content learned by the front end.
Technology: NodeJS, Express, Monk, MongoDB, AngularJS, BootStrap, cross-domain
1. Bootstrap
Bootstrap is a UI framework that supports responsive layouts and performs well on both PC and mobile.
Bootstrap is a simple, intuitive and powerful front-end development framework launched by Twitter.
Bootstrap contains a wealth of Web components, according to these components, you can quickly build a beautiful, fully functional website.
1.1. Add a reference
You can also use the package manager or go to the official website to download and add references.
1.2.Use BootStrap in the page
Add a CSS reference:
Add a JavaScript reference:
Reference the style defined by BootStrap in the page
Bootstrap Hello, world!
This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information
Learn more
Default main success message warning error link default
1.3. Visual layout
Second, create a database using MongoDB
2.1.Starting the MongoDB database
The specific installation and configuration of the database have been explained in the previous chapter, which can be used for reference.
If the service and configuration are not complete, you can start: C:/Program Files/MongoDB/Server/3.4/bin/mongod.exe
2.2.Starting database GUI management tools
2.3. Create databases and collections
Right-click "create database" on localhost to create a database named BookStore.
Create a collection named books for storing books.
Add 5 books to the collection.
Db.getCollection ('books') .insert ({id:201701,title: "developing next-generation applications with AlarJS", picture: "b1.jpg", price:55.0,author: "brad green"})
Third, create an Express project
Here, use Eclipse (HBuilder) as the development tool, add a Nodeclipse plug-in, and add a new Express project:
3.1.Create app.js
/ * Module dependencies. * / var express = require ('express'), routes = require ('. / routes'), books = require ('. / routes/books'), http = require ('http'), path = require (' path'); var app = express (); / / all environmentsapp.set ('port', process.env.PORT | | 3000); app.set (' views', _ 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'); / / development onlyif ('development' = = app.get (' env')) {app.use (express.errorHandler ());} app.get ('/', books.list); app.get ('/ books', books.list) Http.createServer (app) .cake (app.get ('port'), function () {console.log (' Express server listening on port' + app.get ('port'));})
IV. Monk accesses MongoDB database
Monk is a module that accesses MongoDB database under NodeJS platform. It is more convenient for monk to access MongoDB than to access NodeJS directly.
4.1. Create a connection
Const monk = require ('monk') / / Connection URLconst url =' localhost:27017/myproject';const db = monk (url); db.then (() = > {console.log ('Connected correctly to server')})
4.2. Insert data
Const url = 'localhost:27017/myproject'; / / Connection URLconst db = require (' monk') (url) Const collection = db.get ('document') collection.insert ([{a: 1}, {a: 2}) {a: 3}]) .then ((docs) = > {/ / docs contains the documents inserted with added * * _ id** fields / / Inserted 3 documents into the document collection}) .catch ((err) = > {/ / An error happened while inserting}) .then () = > db.close () users.insert ({woot: 'foo'}) users.insert ([{woot:' bar'}, {woot: 'baz'}])
4.3. Update data
Const url = 'localhost:27017/myproject'; / / Connection URLconst db = require (' monk') (url) Const collection = db.get ('document') collection.insert ([{a: 1}, {a: 2}, {a: 3}]) .then ((docs) = > {/ / Inserted 3 documents into the document collection}) .then () = > {return collection.update ({a: 2}) {$set: {b: 1}}) .then ((result) = > {/ / Updated the document with the field an equal to 2}) .then (() = > db.close ()) users.update ({name: 'foo'}, {name:' bar'})
4.4. Delete data
Const url = 'localhost:27017/myproject'; / / Connection URLconst db = require (' monk') (url) Const collection = db.get ('document') collection.insert ([{a: 1}, {a: 2}, {a: 3}]) .then ((docs) = > {/ / Inserted 3 documents into the document collection}) .then () = > collection.update ({a: 2}) {$set: {b: 1}}) .then (result) = > {/ / Updated the document with the field an equal to 2}) .then () = > {return collection.remove ({a: 3})}. Then ((result) = > {/ / Deleted the document with the field an equal to 3}) .then (() = > db.close ()) users.remove ({woot: 'foo'})
4.5, find data
Const url = 'localhost:27017/myproject'; / / Connection URLconst db = require (' monk') (url) Const collection = db.get ('document') collection.insert ([{a: 1}, {a: 2}, {a: 3}]) .then ((docs) = > {/ / Inserted 3 documents into the document collection}) .then () = > collection.update ({a: 2}) {$set: {b: 1}}) .then (result) = > {/ / Updated the document with the field an equal to 2}) .then (() = > collection.remove ({a: 3})) .then (result) = > {/ / Deleted the document with the field an equal to 3}) .then (() = > {return collection.find ()}) .then (docs) = > {/ / docs = = [{a: 1}, {a: 2] B: 1}]}) .then (() = > db.close () users.find ({}). Then ((docs) = > {}) users.find ({}, 'name'). Then ((docs) = > {/ / only the name field will be selected}) users.find ({}, {fields: {name: 1}}) / / equivalentusers.find ({}) '- name') .then ((docs) = > {/ / all the fields except the name field will be selected}) users.find ({}, {fields: {name: 0}) / / equivalentusers.find ({}, {rawCursor: true}). Then ((cursor) = > {/ / raw mongo cursor}) users.find ({}). Each ((user, {close, pause) Resume}) = > {/ / the users are streaming here / / call `close () `to stop the stream}) .then (() = > {/ / stream is over}) / / Database created var monk = require ('monk') var db = monk (' localhost:27017/bookstore') / / read data: var monk = require ('monk') var db = monk (' localhost:27017/monk-demo') var books = db.get ('books') books.find ({}, function (err) Docs) {console.log (docs)}) / / insert data: books.insert ({"name": "orange book", "description": "just so so"}) / / find data: books.find ({"name": "apple book"}, function (err) Docs) {console.log (docs)}) copy code 5. Create a Rest backend service. The contents of the books.js file added under the routes directory are as follows: copy code / * * use monk to access mongodb * provide services to the foreground by rest * / / rely on monk module var monk = require ('monk') / / Connect and open the database var db = monk ('localhost:27017/BookStore'); / / get the books collection from the database, similar to tables, not all data, keyvar books = db.get (' books') / / list all books jsonexports.list = function (req, res) {/ / find all books unconditionally. Then is the asynchronous method books.find ({}). Then ((docs) = > {/ / return json to the client res.json (docs);}). Then (() = > db.close ()); / / close the database} / / get the maximum idexports.getMax=function (req,res) {/ / find one, sort by id descending order, books.findOne ({}, {sort: {id:-1}}). Then ((bookObj) = > {res.json (bookObj);}) .then (() = > db.close () } / / add a book exports.add = function (req, res) {/ / first find the largest book number books.findOne ({}, {sort: {id:-1}}). Then ((obj) = > {/ / the book object sent from the client to the server var book=req.body; / / sets the book number as the largest book number + 1 book.id= (parseInt (obj.id) + 1) + "" / / add books.insert (book) .then ((docs) = > {/ / return successfully added object res.json (docs);}) .then (() = > db.close ());});}; / / delete book exports.del = function (req, res) {/ / take the parameter id,/:id var id=req.params.id from the path / / remove the book books.remove ({"id": id}). Then ((obj) = > {/ / return removal result res.json (obj);}) .then (() = > db.close ());}; / / Update exports.update = function (req, res) {/ / get the json object var book=req.body submitted to the server / / perform the update. The first parameter is the book search condition to be updated, and the second parameter is the object books.update ({"id": book.id}, book). Then ((obj) = > {/ / return the updated object res.json (obj);}) .then (() = > db.close ());}
To complete the cross-domain request, modify the http header information and path mapping. The app.js file is as follows:
Var express = require ('express'), routes = require ('. / routes'), books = require ('. / routes/books'), http = require ('http'), path = require (' path'); var app = express (); / / all environmentsapp.set ('port', process.env.PORT | | 3000); app.set (' views', _ 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')); app.all ('*', function (req, res, next) {res.header ("Access-Control-Allow-Origin", "*"); res.header ("Access-Control-Allow-Headers", "content-type") Res.header ("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); res.header ("X-Powered-By", '3.2.1') res.header ("Content-Type", "application/json;charset=utf-8"); if (req.method = = "OPTIONS") {res.send;} else {next ();}}) / / development onlyif ('development' = = app.get (' env')) {app.use (express.errorHandler ());} app.get ('/', books.list); / / get the list of all books app.get ('/ books', books.list); / / the largest number app.get ('/ books/maxid', books.getMax); / / add app.post ('/ books/book', books.add) / / delete app.delete ('/ books/id/:id', books.del); / / update app.put ('/ books/book', books.update); http.createServer (app) .destroy (app.get ('port'), function () {console.log (' Express server listening on port' + app.get ('port'));})
Testing of other services can be done using Fiddler.
6. Call the backend service using AngularJS
The UI here is completed using BootStrap, and the front end uses AngularJS to call the service published by NodeJS to store the data in the MongoDB.
The index.js page is as follows:
Tian Gou Bookstore .cover {height: 40px; width: auto;} .addBook {padding-top: 10px;} .w100 {width: 50px} .w200 {width: 200px;} .w300 {width: 300px} Toggle navigation Tiangou Bookstore Front end Java .net more types of Action Another action Something else here Separated link One more separated link search
Third Thumbnail label
Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.
New book on shelves × add / edit book number title picture price author save empty close serial number picture price author operation {{index+1} {{b.id}} {{b.title}}
{{b.price | number:1}} {{b.author}} delete the edit / / definition module, specify that the dependency is empty var bookApp = angular.module ("bookApp", []); / / define the controller, specify the name of the controller, $scope is the global object bookApp.controller ("BookController", ['$scope','$http', function ($scope, $http) {$scope.books = []] $scope.save = function () {$http ({url: "http://127.0.0.1:3000/books/book", data: $scope.book, method: $scope.book.id? Success (function (data, status, headers, config) {if ($scope.book.id) {alert ("modified successfully");} else {$scope.books.push (data);}}) .error (function (data, status, headers, config) {alert (status);});} $scope.edit = function (b) {$scope.book = b;} $scope.clear = function () {$scope.book = {} } / / initialize loading $http.get ("http://127.0.0.1:3000/") .success (function (data, status, headers, config) {$scope.books = data;}) .error (function (data, status, headers, config) {alert (status);}) $scope.del = function (id, index) {$http.delete ("http://127.0.0.1:3000/books/id/" + id) .success (function (data, status, headers, config) {$scope.books.splice (index, 1);}) .error (function (data, status, headers, config) {alert (status);});}]) At this point, I believe you have a deeper understanding of "how to develop a bookstore with NodeJS+MongoDB+AngularJS+Bootstrap". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.