资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

怎么用NodeJS+MongoDB+AngularJS+Bootstrap开发书店

本篇内容主要讲解“怎么用NodeJS+MongoDB+AngularJS+Bootstrap开发书店”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用NodeJS+MongoDB+AngularJS+Bootstrap开发书店”吧!

公司主营业务:成都网站设计、成都网站制作、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联建站是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联建站推出长垣免费做网站回馈大家。

示例名称:天狗书店

功能:完成前后端分离的图书管理功能,总结前端学习过的内容。

技术:NodeJS、Express、Monk、MongoDB、AngularJS、BootStrap、跨域

一、Bootstrap

Bootstrap是一个UI框架,它支持响应式布局,在PC端与移动端都表现不错。

Bootstrap是Twitter推出的一款简洁、直观、强悍的前端开发框架。

Bootstrap中包含了丰富的Web组件,根据这些组件,可以快速的搭建一个漂亮、功能完备的网站。

1.1、添加引用

也可使用包管理器也可以去官网下载后添加引用。

1.2、在页面中使用BootStrap

添加CSS引用:

添加JavaScript引用:

在页面中引用BootStrap定义好的样式

   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 

 
 
   默认 主要 成功 信息 警告 错误 链接 
  默认 默认 默认 默认      

1.3、可视化布局

二、使用MongoDB创建数据库

2.1、启动MongoDB数据库

数据库的具体安装、配置在前面的章节中已经讲解过,可以参考。

如果服务与配置都没有完成的话可以启动:C:/Program Files/MongoDB/Server/3.4/bin/mongod.exe

2.2、启动数据库GUI管理工具

2.3、创建数据库与集合

 在localhost上右键“create database”创建名称为BookStore的数据库。

创建一个用于存放图书的集合名称为books。

在集合中添加5本图书。

db.getCollection('books').insert({id:201701,title:"使用AlarJS开发下一代应用程序",picture:"b1.jpg",price:55.0,author:"brad green"});

三、创建一个Express项目

这里使用Eclipse(HBuilder)为开发工具,添加Nodeclipse插件,新增一个Express项目:

3.1、创建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).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port'));});

四、Monk访问MongoDB数据库

monk是NodeJS平台下访问MongoDB数据库的一个模块。monk访问MongoDB更加方便比NodeJS直接访问。

4.1、创建连接

const monk = require('monk')// Connection URLconst url = 'localhost:27017/myproject';const db = monk(url);db.then(() => { console.log('Connected correctly to server')})

4.2、插入数据

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、更新数据

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 a equal to 2 }) .then(() => db.close())users.update({name: 'foo'}, {name: 'bar'})

4.4、删除数据

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 a equal to 2 }) .then(() => { return collection.remove({ a: 3}) }).then((result) => { // Deleted the document with the field a equal to 3 }) .then(() => db.close())users.remove({ woot: 'foo' })

4.5、查找数据

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 a equal to 2 }) .then(() => collection.remove({ a: 3})) .then((result) => { // Deleted the document with the field a 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})//创建的数据库var monk = require('monk')var db = monk('localhost:27017/bookstore')//读取数据:var monk = require('monk')var db = monk('localhost:27017/monk-demo')var books = db.get('books') books.find({}, function(err, docs) { console.log(docs)})//插入数据:books.insert({"name":"orange book","description":"just so so"})//查找数据:books.find({"name":"apple book"}, function(err, docs) { console.log(docs)})复制代码五、创建Rest后台服务在routes目录下增加的books.js文件内容如下:复制代码/* * 使用monk访问mongodb * 以rest的方式向前台提供服务 *///依赖monk模块var monk = require('monk');//连接并打开数据库var db = monk('localhost:27017/BookStore');//从数据库中获得books集合,类似表,并非所有数据, keyvar books = db.get('books');//列出所有的图书jsonexports.list = function(req, res) { //无条件查找所有的图书,then是当查找完成时回调的异步方法 books.find({}).then((docs) => { //返回json给客户端 res.json(docs); }).then(() => db.close()); //关闭数据库};//获得最大idexports.getMax=function(req,res){ //找一个,根据id降序排序, books.findOne({}, {sort: {id: -1}}).then((bookObj)=>{ res.json(bookObj); }).then(() => db.close());;}//添加图书exports.add = function(req, res) { //先找到最大的图书编号 books.findOne({}, {sort: {id: -1}}).then((obj)=>{ //从客户端发送到服务器的图书对象 var book=req.body; //设置图书编号为最大的图书编号+1 book.id=(parseInt(obj.id)+1)+""; //执行添加 books.insert(book).then((docs) => { //返回添加成功的对象 res.json(docs); }).then(() => db.close()); });};//删除图书exports.del = function(req, res) { //从路径中取参数id,/:id var id=req.params.id; //移除编号为id的图书 books.remove({"id":id}).then((obj)=>{ //返回移除结果 res.json(obj); }).then(() => db.close());};//更新exports.update = function(req, res) { //获得提交给服务器的json对象 var book=req.body; //执行更新,第1个参数是要更新的图书查找条件,第2个参数是要更新的对象 books.update({"id":book.id}, book).then((obj)=>{ //返回更新完成后的对象 res.json(obj); }).then(() => db.close());};

为了完成跨域请求,修改http头部信息及路径映射,app.js文件如下:

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("200"); } else { next(); }});// development onlyif('development' == app.get('env')) { app.use(express.errorHandler());}app.get('/', books.list);//获得所有的图书列表app.get('/books', books.list);//最大的编号app.get('/books/maxid', books.getMax);//添加app.post('/books/book', books.add);//删除app.delete('/books/id/:id', books.del);//更新app.put('/books/book', books.update);http.createServer(app).listen(app.get('port'), function() { console.log('Express server listening on port ' + app.get('port'));});

其它服务的测试可以使用Fiddler完成。

六、使用AngularJS调用后台服务

这里的UI使用BootStrap完成,前端使用AngularJS调用NodeJS发布的服务,将数据存放在MongoDB中。

index.js页面如下:

   天狗书店     .cover { height: 40px; width: auto; } .addBook { padding-top: 10px; } .w100 { width: 50px } .w200 { width: 200px; } .w300 { width: 300px }          Toggle navigation 天狗书店     前端  
  •  Java 
  •  
  •  .Net 
  •   更多类型  
  •  Action 
  •  
  •  Another action 
  •  
  •  Something else here 
  •    
  •  Separated link 
  •    
  •  One more separated link 
  •         搜索                             
     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. 

                   新书上架     ×  添加/编辑图书      编号      书名      图片      价格      作者          保存   清空   关闭          序号   编号   书名   图片   价格   作者   操作       {{$index+1}}   {{b.id}}   {{b.title}}      {{b.price | number:1}}   {{b.author}}   删除 编辑             //定义模块,指定依赖项为空 var bookApp = angular.module("bookApp", []); //定义控制器,指定控制器的名称,$scope是全局对象 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 ? "PUT" : "POST" }) .success(function(data, status, headers, config) { if($scope.book.id) { alert("修改成功"); } 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 = {}; } //初始化加载 $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); }); } }]);  

    到此,相信大家对“怎么用NodeJS+MongoDB+AngularJS+Bootstrap开发书店”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!


    当前名称:怎么用NodeJS+MongoDB+AngularJS+Bootstrap开发书店
    本文链接:http://cdkjz.cn/article/gehedd.html
    多年建站经验

    多一份参考,总有益处

    联系快上网,免费获得专属《策划方案》及报价

    咨询相关问题或预约面谈,可以通过以下方式与我们联系

    大客户专线   成都:13518219792   座机:028-86922220