node+express+mongoose快速搭建電影網站

來源:互聯網
上載者:User

       本文主要是學習了Scott老師的建站攻略一的學習筆記。  1.搭建環境

       使用node的npm工具進行安裝前後端需要使用到的架構或類,搭建電影網站需要用到的架構如下:

   

          後端:(使用npm安裝)

               Mongoose:對MongoDB進行快速建模的工具

               MongoDB:Nosql資料庫

             Jade:用戶端的模板引擎

             Moment.js:日期格式化

        前端:(npm安裝Bower,Bower安裝其他前端庫)

                jQuery類庫

               Bootstrap架構         具體操作:首先進入到建立項目的根目錄下,然後利用npm進行安裝

        npm  install express //後台架構會使用

        npm install body-parser //新版的express沒有內建,用於解析用戶端請求的body中的內容,內部使用JSON編碼處理,url編碼處理以及對於檔案的上傳處理.

        npm  install jade  //模板引擎的使用

        npm install underscore //Underscore封裝了常用的JavaScript對象操作方法,用於提高開發效率

        npm install moment  //時間格式化處理類

        npm  install mongoose

        npm  install bower -g

        bower install bootstrap


      為了方便項目中資源檔,我們在根目錄下建立一個檔案夾public,在public中建立一個libs檔案夾,將bwer_components中的檔案拷貝進去。  2.項目頁面和功能分析


該項目的功能主要是:展示所有電影的首頁index,點擊首頁中一部電影可以查看器詳細內容detail,還有一個錄入電影相關資訊的介面admin,以及電影列表頁list,可以對電影進行刪除、修改等操作。 3.編寫前端的頁面

根據功能要求,使用jade的方式編寫前端頁面,主要是views中檔案。includes中是pages中頁面的公用部分內容,layout.jade是頁面的布局。


4.後端資料模型的構建

定義項目中的模型movie,這裡定義了一個Schema:MovieSchem,在定義Schema時,還可以設一些預設值、驗證什麼的,但這裡先忽略。

var mongoose = require('mongoose')

//骨架模版
var MovieSchema = new mongoose.Schema({
    doctor:String,
    title:String,
    language:String,
    country:String,
    year:Number,
    summary:String,
    flash:String,
    poster:String,
    meta:{
        createAt:{
            type:Date,
            default:Date.now()
        },
        updateAt:{
            type:Date,
            default:Date.now()
        }
    }
})

var Movie = mongoose.model('Movie',MovieSchema)  //這一句中,第一個參數相當重要,它是給MovieSchema這個schema,定義了一個名字Movie

module.exports = Movie //使用module.exports將其匯出是使其外部可用
5.express架構的使用

建立server:

var express = require('express')
var path = require('path')

//設定連接埠,process全域變數
var port = process.env.PORT || 3000


//資料庫連接類 var mongoose = require('mongoose')
var _ = require('underscore')
var Movie = require('./models/movie')


//串連資料庫: 連接字串格式為mongodb://主機/資料庫名
mongoose.connect('mongodb://localhost/imooc')

//啟動web伺服器

var express = require('express')
var app = express()


//將執行個體賦給變數,配置視圖
app.set('views','./views/pages')
//設定預設的模板引擎

app.set('view engine','jade')


//表單資料格式化

var bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({extended:true}))


//設定資源路徑
app.use(express.static(path.join(__dirname,'public')))
app.locals.moment = require('moment')
//監聽連接埠
app.listen(port)


//編寫url路由

/首頁面index page的路由
app.get('/',function(req,res){
  Movie.fetch(function(err,movies){
    if (err) {
      console.log(err)
    }

    res.render('index',{
      title:'immoc 首頁',
      movies:movies
    })
  })
})

//詳情頁面detail的路由
app.get('/movie/:id',function(req,res){
    var id = req.params.id
    
    Movie.findById(id,function(err,movie){
      res.render('detail',{
       title:'immoc '+movie.title,
       movie:movie
      })
    })
})

//admin頁面admin page的路由
app.get('/admin/movie',function(req,res){
    res.render('admin',{
       title:'immoc 後台錄入頁面' ,
       movie:{
        title:'',
        doctor:'',
        country:'',
        year:'',
        poster:'',
        flash:'',
        summary:'',
        language:''
       }
    })
})

//admin update movie
app.get('/admin/updat:id',function(req,res){
  var id = req.params.id

  if (id) {
     Movie.findById(id,function(err,movie){
      res.render('admin',{
        title:'immoc 後台更新頁',
        movie:movie
      })
    })
  }
})

//admin post movie
app.post('/admin/movie/new',function(req,res){
  var movieObj = req.body.movie
  var id = req.body.movie._id
  var _movie
 
  if (id !== 'undefined') {
    Movie.findById(id,function(err,movie){
      if (err) {
        console.log(err)
      }

      _movie = _.extend(movie,movieObj)

      _movie.save(function(err,movie){
        if (err) {
          console.log(err)
        }

        res.redirect('/movie/'+movie._id)
      })

    })
  }else{
    _movie = new Movie({
      doctor:movieObj.doctor,
      title:movieObj.title,
      country:movieObj.country,
      language:movieObj.language,
      year:movieObj.year,
      poster:movieObj.poster,
      summary:movieObj.summary,
      flash:movieObj.flash
    })

     _movie.save(function(err,movie){
        if (err) {
          console.log(err)
        }

        res.redirect('/movie/'+movie._id)
    })
  }
})

//list頁面list page的路由
app.get('/admin/list',function(req,res){
  Movie.fetch(function(err,movies){
    if (err) {
      console.log(err)
    }

    res.render('list',{
      title:'immoc 列表頁',
      movies:movies
    })
  })
})

//list delete movie
app.delete('/admin/list',function(req,res){
  var id = req.query.id

  if(id){
    Movie.remove({_id:id},function(err,movie){
      if (err) {
        console.log(err)
      }else{
        res.json({success:1})
      }
    })
  }
})


6.項目啟動運行      

進入根目錄,運行 node app.js

在瀏覽中開啟index頁面:http://localhost:3000

整個項目的源碼:code

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.