使用Node.js和MongoDB通过Mongoshin和Express.js构建JSON REST API服务器

根据《JavaScript快速全栈开发》书籍和网络上的融合整理出,方便自己和大家以后学习交流哒,更加为了自己整理笔记--

将使用Mocha和Super Agent库写测试,然后使用测试驱动的方式用Express.js、MongoDBD Mongoshin库开发一个免费的Node.js JSON Rest API服务器。

1.先创建一个用于保存测试文件的文件夹。可以人工创建也可以代码创建。(我的路径D:\A_Learn\Node.js\anzhuangmulu\NodeTest\rest-api)

mkdir rest-api

cd rest-api

2.用cmd进入存放node.js的目录里安装Mocha、Exppect.js和Super Agent库。

npm install mocha


npm install expect.js


npm install supperagent


3.【测试覆盖率】使用Super Agent的链式调用函数。写一个完整的express.test.js测试覆盖率,放入刚才创建的rest-api里面(我的地址是D:\A_Learn\NodeJS\anzhuangmulu\NodeTest\rest-api)

var superagent = require('superagent')
var expect = require('expect.js')
describe('express rest api server',function(){
	var id
	it ('post object',function(done){
		 superagent.post('http://localhost:3000/collection/test')
			.send({name:'John',email:'john@rpjs.co'})
			.end(function(e,res){
				 expect(e).to.eql(null)
				 expect(res.body.length).to.eql(1)
				 expect(res.body[0]._id.length).to.eql(24)
				 id = res.body[0]._id
				 done()
			})
	})
	it('retrieves an object',function(done){
		 superagent.get('http://localhost:3000/collections/test/'+id)
			 .end(function(e,res){
				 expect(e).to.eql(null)
				 expect(typeof res.body).to.eql('object')
				 expect(res.body._id.length).to.eql(24)
				 expect(res.body._id).to.eql(id)
				 done()
		 })
	})
	it('retrieves a collection',function(done){
		 superagent.get('http://localhost:3000/collections/test')
			 .end(function(e,res){
				 expect(e).to.eql(null)
				 expect(res.body.length).to.be.above(1)
				 expect(res.body.map(function(item){
					 return item._id
			 })).to.contain(id)
			 done()
		 })			
	})
	it('updates an object',function(done){
		 superagent.get('http://localhost:3000/collections/test/'+id)
			 .send({name:'Peter',email:'peter@yahoo.com'})
			 .end(function(e,res){
					 expect(e).to.eql(null)
					 expect(typeof res.body).to.eql('object')
					 expect(res.body.msg).to.eql('success')
					 done()
			 })
	})
	it('checks an uodated object',function(done){
		 superagent.get('http://localhost:3000/collections/test/'+id)
			 .end(function(e,res){
				 expect(e).to.eql(null)
				 expect(typeof res.body).to.eql('object')
				 expect(res.body._id.length).to.eql(24)
				 expect(res.body._id).to.eql(id)
				 expect(res.body.name).to.eql('Peter')
				 done()
		     })		 
	})
	it('removes an object',function(done){
		 superagent.get('http://localhost:3000/collections/test/'+id)
			 .end(function(e,res){
				 expect(e).to.eql(null)
				 expect(typeof res.body).to.eql('object')
				 expect(res.body.msg).to.eql('success')
				 done()
			 })
	})
})
最后cmd进入到D:\A_Learn\NodeJS\anzhuangmulu\NodeTest\rest-api后运行$mocha express.test.js命令,即可查看到6条信息。

(4)【依赖】将要使用Mongoskin,它是一个MongoDB库,比原生MongoDB驱动好用。Express.js是Node.js核心模块的包装器,它下Connect中间件的基础上构建而来,提供了大量的方便。

用cmd进入到node_modules目录中进行安装

npm install express

npm install -g mongoskin

npm install -g mogodb(因为还要用到mongo所以也要安装mongo哦.这个是全局安装mongodb否则会报找不到mongo的错误)

新建一个ecpress.js放入rest-api目录中

var express = require('express'),mongoskin = require('mongoskin')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
var db = mongoskin.db('localhost:27017/test',{safe:true});
app.param('collectionName',function(req,res,next,collectionName){
	 req.collection = db.collection(collectionName)
	 return next()
})
app.get('/',function(req,res){
	 res.send('please select a collection,'+'e.g.,/collections/messages')		
})
app.get('/collections/:collectionName',function(req,res){
		req.collection.find({},{limit:10,sort:[['_id',-1]]})
		.toArray(function(e,results){
			 if(e) return next(e)
				 res.send(results)
		})
})
app.post('/collections/:collectionName',function(req,res){
		 req.collection.insert(req.body,{},function(e,results){
			 if(e) return next(e)
			 res.send(results)
		 })	 
})
app.get('/collections/:collectionName/:id',function(req,res){
			 req.collection.findOne({_id:req.collection.id(req.params.id)},function(e,result){
				if(e) return next(e)
				 res.send(result)
			 })
})
app.put('/collections/:collectionName/:id',function(req,res){
			req.collection.update({_id:req.collection.id(req.params.id)},{$set:req.body},{safe:true,multi:false},function(e,result){
				 if(e) return next(e)
					 res.send((result===1) ? {msg:'success'} : {msg:'error'})
			})	
})
app.delete('/collections/:collectionName/:id',function(req,res){
			req.collection.remove({_id:req.collection.id(req.params.id)},function(e,result){
				 if(e) return next(e)
				 res.send((result === 1) ? {msg:'success'} : {msg:'error'})
			})	 
})
app.listen(3000)
在终端运行node express.js

在另外一个窗口(不要关闭之前那个)运行mocha  express.test.js

还可以在浏览器中查看比如http://localhost:3000/test

延伸:以前写成以下时会报下面的错误

var express = require('express'),mongoskin = require('mongoskin')
var app = express()
app.use(bodyParser())

这是因为express3和express4的区别:参考文献:http://www.expressjs.com.cn/guide/migrating-4.html#overview

所以改成了下面这样并且在node-moudle里面引入body-parser (npm install body-parser):

var express = require('express'),mongoskin = require('mongoskin')
var bodyParser = require('body-parser')
var app = express()
运行了发现还报错误:body-parser deprecated bodyParser:use indiidual json/urlencoded middewares express.js:4:9

因此在里面加上

var express = require('express'),mongoskin = require('mongoskin')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.urlencoded({extended:false}))app.use(bodyParser.json())



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值