使用node.js ,Express, 和Mongodb 简历一个简单的Restful 网页服务-part1

5 篇文章 0 订阅
2 篇文章 0 订阅

使用node.js ,Express, 和Mongodb 简历一个简单的Restful 网页服务-part1

这个实现的基础是《使用handlebars 代替Jade 使用Express》 ,或者可以直接下载开始的源码,根据下面的步骤进行编辑

$ git clone https://susan200893171@bitbucket.org/susan200893171/node-js-example.git 
$ cd node-js-exmaple ;git checkout jadeToHandlebars
$ cd node-js-example
$ npm install
$ npm start 

在这篇文章中,主要是记录如何使用mongoose,添加数据,handlebars 的一些基本的使用。
为了比较清楚的了解,首先创建页面
这里写图片描述

因为这边文章主要是针对nodejs Express, mongoose讲解,你可以直接粘贴下面的代码到相应的文件里 。

1、 进入 views/layouts , 编辑main.handlebars,

node-js-example/views/layout/main.handlebars
<head>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>

2、 在views 文件夹中创建users.handlebars

node-js-example/views/users.handlebars
<script type="text/javascript" src="/javascripts/users.js"></script>
<div class="container">
 <div class="row">
   <div class="col-sm-6">
     <div id="addUserForm">
       <h1>Add New User</h1>
         <form role="form">
           <div class="form-group">
             <label for="name">Name:</label>
             <input type="text" id="username" class="form-control" name=name>
           </div>
          <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" id="useremail" class="form-control" name="email">
          </div>
          <button type="button" class="btn btn-default" id="add" name="Add">添加</button>
       </form>
     </div>
     <div id="showUserInfo">
         <!--之后添加-->
      </div>
   </div>
   <div class="col-sm-6">
     <h1> Show the User's information</h1>
       <div class="table-responsive">
         <table class="table" id="usersTable">
           <thead>
             <th>Name</th>
             <th>Email</th>
             <th>Delete?</th>
           </thead>
           <tbody>
             {{#each users}}
             <tr>
               <td><a href="#" rel="{{name}}">{{name}}</a></td>    
               <td>{{email}}</td>
               <td><a href="#" rel="{{_id}}">Delete?</a></td>
             </tr>
             {{/each}}
          </tbody>
        </table>
       </div>
    </div>
</div>

3、 在public/javascripts/ 文件夹中,建立users.js 文件,这个是在users.handlebars 第一行中引用的文件,因为在app.js 文件中我们引用了app.use(express.static(path.join(__dirname, 'public')));
users.js 文件内容如下,如果没有javascripts 文件夹,直接创建:

node-js-example/public/
$ mkdir javascripts
node-js-example/public/javascripts/users.js
$(document).ready(function(){
   $('#add').on('click',addUser);
});
function addUser(event){
        event.preventDefault();
        var newUser = {
                name:$("#username").val(),
                email:$("#useremail").val(),
        };
        console.log('new user='+newUser);
        //use AJAX to post object to our adduser service
        $.ajax({
                type:'POST',
                data: newUser,
                url : '/users/adduser',
                dataType:'JSON'
        }).done(function(response){
                console.log(response);
                if(response.message === ''){
                        //post correct ,
                        //刷新数据 {{uses}}
                        window.location.href='/users/';
                }else{
                };
        });
}

添加的数据格式是{name:…,email:…}
4、 使用mongoose 对数据库进行操作。
MongoDB 在mac上安装已经讲解了如何安装。
创建data文件夹启动数据库

node-js-example/
$mkdir data
$cd data
$mongod --dbpath .

我建立一个credentials.js 文件,保留一些配置文件,之后可以添加其他的一个配置,现在只是数据库的url

node-js-example/credentials.js
module.exports={
        database:{
                         url:'mongodb://127.0.0.1:27017/blog',
                 },
}

因为是使用mongoose,首先安装mongoose

node-js-example/
$npm install --save mongoose

我建立一个models文件保存数据的格式

node-js-example/
$ mkdir models 
$ cd models
$ touch user.js

mongodb是使用shema来确定数据库的格式,在/public/javascripts/users.js 中ajax post newUser 的格式是{name,email} ,所以models/user.js 的内容

node-js-example/models/users.js
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
        name:String,
        email:String,
});
var User = mongoose.model('User',userSchema);

module.exports = User;

建立完数据格式,我们需要把express 和数据库链接起来。
打开app.js 文件,添加如下代码:

node-js-example/app.js
var mongoose = require('mongoose');
var credentials = require('./credentials.js');
mongoose.connect(credentials.database.url);

5 、 数据库连接之后,我们需要对路径/users 进行操作,因为在app.js 中

node-js-example/app.js
var users = require('./routes/users');
app.use('/users',users);

所以进入routes 文件夹打开 users.js 文件

node-js-example/
$ vi routes/users.js 

因为在routes/users.js文件中有对数据库操作,所以添加

node-js-example/routes/users.js
var User = require('../models/user.js');

首先为了得到如图片所示的界面,首先对 get(‘/’,function(req,res)) 进行编辑

node-js-example/routes/users.js
router.get('/',function(req,res){
    //因为在文件views/users.handlebars中{{#each users}} 所以需要访问数据库得到所有的users
    User.find(function(err,docs){
        if(err){
           res.send({message:err});
        }else{
            res.render('users',{users:docs});
        }  
    });
});

添加完这段之后,可以运行,之后出现如图的界面

node-js-example/
$ npm start 

在添加user的是,ajax post 操作,所以需要添加 post /users/adduser , 添加如下代码

node-js-example/routes/users.js
router.post('/adduser',function(req,res){

        var body=req.body;
        var newUser = new User({
                name:body.name,
                email:body.email
        });
        newUser.save(function(err){
                if(err){
                        //if there is some error ,when saving into the database
                        //send back to error
                        res.send({message:err});
                }else{
                        //insert sucessfully, send back nothing
                         res.send({message:'',newUser:newUser});
                }
        });
});

之后运行

node-js-example/
$ npm start 

完整的这部分代码:

$ git clone https://susan200893171@bitbucket.org/susan200893171/node-js-example.git 
$ cd node-js-example
$ git checkout mongoose
$ npm install 
$ npm start

然后打开browser , 输入http://localhost:3000/users/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值