This document is based on video learning on MOOCs
Topic:
Introduction to development Framework
The development framework is described in the figure above
Project development process
Prototype drawing – Home page, detail page
Background entry page
Chapter 2: The process of the front and back end of the project is cleared up
2.1 Node entry file analysis and directory initialization
2.2. Create four JADE views and process them in entry files
- Create a project directory iMOOc
- Create app.js and views directory in the root directory
npm init
npm install express jade moment mongoose
- Create app.js and write the entry file:
# app. Js var express = the require (' express ') / / loaded express this module var port = process. The env. The port | | / 3000 / set port: Var app = express()// Start a Web server app.set('views','./views')// Set the root of the view app.set('view ') Engine ','jade')// Set the default template engine app.listen(port)// listen to port console.log('imooc started on port '+ port)// Print a log, // add route //index page app.get('/index',function(req,res){ Res.render ('index',{title:'imooc home '})}) //detail page app.get('/movie/:id',function(req,res){ Function (req,res){res.render('detail',{title:'detail '})}) function(req,res){res.render('detail',{title:'detail '})}) Get ('/admin/movie',function(req,res){res.render('admin',{title:'imooc })})Copy the code
The project structure is:
doctype html head meta(chaset=”utf-8″) title #{title} body h1 #{title}
#@ Open the project in terminal and enter node app.js to check whether it is started correctly (PORT=40000 node app.js can also be started) # enter the address in browser: Localhost: 3000 / index, localhost: 3000 / list, localhost: 3000 / admin/movie, localhost: 3000 / admin / 01 check whether it is right.Copy the code
2.3. Forged template data runs through the front and back end interaction process
Modify directory structure – use jade syntax can inherit the advantages and call the common block new folder includes folder, Pages folder and layout. Jade layout file in the views, move the original four files in the views to the pages file. Create the head.jade file and header.jade file in the includes file
Layout.jade (Please remove the comment when copy code, there may be an error)
Doctype HTML head meta(chaset=" UTF-8 ") title #{title} include./includes/head //- Abstract a common style into a block body include ./includes/header //- Website title or logo block Content //- Content in each pageCopy the code
Before writing head.jade and header.jade files, we first install Bower, Bootstrap NPM install bower -g bower install [email protected] // If you do not add @3.3.7, the latest version will be installed, resulting in some display problems on the page.
Head.jade (Write the introduced public style)
link(href="/bootstrap/dist/css/bootstrap.min.css", rel="stylesheet")
script(src="/jquery/dist/jquery.min.js")
script(src="/bootstrap/dist/js/bootstrap.min.js")
Copy the code
header.jade
.container.row. page-header H1 #{title} h3 Six weeksCopy the code
Change the contents of four files in Pages to:
extends .. /layoutCopy the code
After successful installation, the project structure looks like this:
At this point, we enter the command node app to check whether ###### can be accessed correctly. Note that the path of accessing the file in app.js is changed
If the access is still successful, proceed to the next step. We start the file encoding for Index.jade (front page) :.
extends .. /layout block content .container .row each item in movies .col-md-2 .thumbnai a(href="/movie/#{item._id}") img(src="#{item/poster}",alt="#{item.title}") .caption h3 #{title} p: A.btn.btn-primary (href="/movie/#{item._id}",role="button") watch the trailerCopy the code
Detail.jade (Detail page) Document:
extends .. /layout block content .container .row .col-md-7 img(src="#{movie.poster}",alt="#{movie.title}",height="720") .col-md-5 Dl. horizontal DT Dd = movie.title DT Dd = movie.doctor dt Country DD = movie.country DT Language DD = movie.Language DT Year of release Dd = movie.year dt Dd = movie.summaryCopy the code
Admin.jade (background input page) file:
extends .. /layout block content .container .row form.form-horizontal(method="post",action="/admin/movie/new") .form-group Control-label (for="inputTitle") Specifies the name of the movie. Col-sm-10 input#inputTitle.form-control(type="text",name="movie[title]",value="#{movie.title}") .form-group Control-label (for="inputDoctor") Movie director.col-sm-10 input#inputTitle.form-control(type="text",name="movie[doctor]",value="#{movie.doctor}") .form-group Label. Col - sm - 2. The control - label (for = "inputCountry") countries. Col - sm - 10 input#inputTitle.form-control(type="text",name="movie[country]",value="#{movie.country}") .form-group Label. Col - sm - 2. The control - label (for = "inputLanguage") languages. Col - sm - 10 input#inputTitle.form-control(type="text",name="movie[language]",value="#{movie.language}") .form-group Control-label (for="inputPoster") poster address. Col-sm-10 input#inputTitle.form-control(type="text",name="movie[poster]",value="#{movie.poster}") .form-group Control-label (for="inputFlash") Source address. Col-sm-10 input#inputTitle.form-control(type="text",name="movie[flash]",value="#{movie.flash}") .form-group Control-label (for="inputSummary").col-sm-10 textarea#inputSummary. Form-control (type="text", name="movie[summary]", Value ="#{movie.summary}").form-group.col-sm-offset-2.col-sm-10 button.btn.btn-default(type="submit"Copy the code
List.jade (list page) file:
extends .. Table -hover. Table -bordered thead tr th Movie name th Director th Country th Release year //-th Tbody each item in movies tr(class="item-id-#{item._id}") TD #{item.title} td #{item.doctor} td #{item.country} td #{item.year} //-td #{moment(item.meta.createAt).format('MM/DD/YYYY')} td :a(target="_blank",href=".. / movie / # {item. _id} ") to check the td: a (target = "_blank" href = ".. /admin/update/#{item._id}") modify td button.btn.btn-danger. Del (type="button",data_id="#{item._id}") deleteCopy the code
Forged static data: app.js
Var app = express() var path =require('path') var port =require('path' Process. The env. PORT | | / 3000 / set PORT: App.set ('views','./views/pages') // Sets the root directory of the view app.set('view engine',' Jade ')// Sets the default template engine var bodyParser = require('body-parser') app.use(bodyParser.json()) app.use(express.static(path.join(__dirname,'bower_components'))) App.listen (port)// Console. Log (' 6 weeks started on port '+ port) // add route //index page app.get('/index',function(req,res){ Res.render ('index',{title:' 6 weeks home ', movies:[{title:' node.js guidelines ', _id:1, Poster: 'http://img4.imgtn.bdimg.com/it/u=1178625225, & FM = 26 & gp = 0. 3686148785 JPG'}, {title: 'Node. Js guidelines, _id: 2, Poster: 'http://img4.imgtn.bdimg.com/it/u=1178625225, & FM = 26 & gp = 0. 3686148785 JPG'}, {title: 'Node. Js guidelines, _id: 3, Poster: 'http://img4.imgtn.bdimg.com/it/u=1178625225, & FM = 26 & gp = 0. 3686148785 JPG'}, {title: 'Node. Js guidelines, _id: 4, Poster: 'http://img4.imgtn.bdimg.com/it/u=1178625225, & FM = 26 & gp = 0. 3686148785 JPG'}, {title: 'Node. Js guidelines, _id: 5, Poster: 'http://img4.imgtn.bdimg.com/it/u=1178625225, & FM = 26 & gp = 0. 3686148785 JPG'}, {title: 'Node. Js guidelines, _id: 6. Poster: 'http://img4.imgtn.bdimg.com/it/u=1178625225, & FM = 26 & gp = 0. 3686148785 JPG'}, {title: 'Node. Js guidelines, _id: 7, Poster: 'http://img4.imgtn.bdimg.com/it/u=1178625225, & FM = 26 & gp = 0. 3686148785 JPG'}, {title: 'Node. Js guidelines, _id: 8, Poster: 'http://img4.imgtn.bdimg.com/it/u=1178625225, & FM = 26 & gp = 0. 3686148785 JPG'}, {title: 'Node. Js guidelines, _id: 9, Poster: 'http://img4.imgtn.bdimg.com/it/u=1178625225, & FM = 26 & gp = 0. 3686148785 JPG'}, {title: 'Node. Js guidelines, _id: 10, Poster: 'http://img4.imgtn.bdimg.com/it/u=1178625225, & FM = 26 & gp = 0. 3686148785 JPG'},]})}) / / detail page App.get ('/movie/:id',function(req,res){res.render('detail',{title:'detail ', movie:{doctor:' 6 weeks ', Counter :'China', title:' China', year:2019, Poster: 'http://img4.imgtn.bdimg.com/it/u=1178625225, & FM = 26 & gp = 0. 3686148785 JPG', language: 'Chinese' flash: 'https://www. Life is too short to do something that no one wants. - Ash Maurya. 2. if you give someone a program, you will torture him all day. If you teach someone how to program, you will torture him for life. - David Leinweber. 3, there are two ways of software design: one way is to make the software too simple, obviously without defects; Another way is to make the software so complex that there are no obvious flaws. - C.A.R. Hoare. 4. Software development tends to be like this: the first 90% of code takes up the first 90% of development time; The remaining 10% of the code also takes 90% of the development time. -- Tom Cargill'}})}) //admin page app.get('/admin/movie',function(req,res){res.render('admin',{title:' 6 weeks movie:{ title:'', doctor:'', country:'', year:'', poster:'', flash:'', summary:'', Function (req,res){res.render('list',{title:' 6 '); Movies :[{title:' node.js ', _id:1, doctor:' 6 weeks ', Country :'China', year:2019, language:' Chinese ', Flash: 'https://www.jianshu.com/u/5842abb77bd1', the summary: '1. Life is too short, don't go to do something that no one wanted to. - Ash Maurya. 2, If you give someone a program, you will torture them for a day; if you teach someone how to program, you will torture them for a lifetime. One way is to make the software so simple that there are no obvious defects, and the other way is to make the software so complex that there are no obvious defects. -- C.A.R. Hoare. The first 90 percent of the code takes up 90 percent of the development time; the remaining 10 percent also takes 90 percent of the development time.Copy the code
})
Then, the error prone area is the page style caused by bootstrap version installation and the indentation of Jade’s code. After some adjustment, start the ‘Node app, and the effect picture is as follows:
##### then, submit the code to git to the code cloud. Code cloud address: gitee.com/ShaoBingYou…
Chapter three: project database implementation
3.1 design and coding of mongodb mode type and database interaction code
In the project root directory, create folders Schemas, Models, controllers. Add the movie.js file to the schemas and models as follows:
schemas-movie.js
var mongoose =require('mongoose')
var MovieSchema =new mongoose.Schema({
doctor:String,
title:String,
language:String,
country:String,
summary:String,
flash:String,
poster:String,
year:Number,
meta:{
createaAt:{
type:Date,
default:Date.now()
},
updataAt:{
type:Date,
default:Date.now()
}
}
})
MovieSchema.pre('save',function(next){
if(this.isNew){
this.meta.createaAt = this.meta.updataAt =Date.now()
}else{
this.meta.updataAt =Date.now()
}
next()
})
MovieSchema.statics = {
fetch:function(cb){
return this
.find({})
.sort('meta.updateAt')
.exec(cb)
},
fingdById:function(id,cb){
return this
.findOne({_id:id})
.exec(cb)
}
}
module.exports =MovieSchema
Copy the code
models-movie.js
var mongoose =require('mongoose') var MovieSchema = require('.. /schemas/movie') var Movie = mongoose.model('Movie',MovieSchema) module.exports = MovieCopy the code
The pattern and model code is finished and we move on to the next chapter.
3.2. Write database interaction code
Entering the app.js file, adding code requires the underscore module to be installed in the terminal: NPM Install underscore
var mongoose = require('mongoose') mongoose.connect('mongodb://localhost/imooc') var Movie =require('./models/movie') Var _ =require('underscore') # underscore all static data in app.jsCopy the code
Add method movie.fetch () to index route and list route. Add method movie.findById () to detail route. Add method app.post() to admin route.
// admin post movie
app.post('/admin/movie/new',function(req,res){
var id =req.body.movie._id
var movieObj =req.body.movie
var _movie
if(id!== 'undefined'){
Movie.findById(id,function(err,mmovie){
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)
})
}
})
Copy the code
All that is needed is to go back to the background entry page when you click update on the list page, re-initialize the data from the form into the form, and add a route
//admin update app.get('/admin/update/:id',function(req,res){ var id =req.params.id if(id){ Movie.findbyid (id,function(err, Movie){res.render('admin',{title:' 6 weeks background update page ', Movie: Movie})})Copy the code
Finally, you need to add a hidden form field on the Admin entry page (admin.jade) to store the movie ID for updates
input(type="hidden",name="movie[_id]",value="#{movie._id}")
Copy the code
Then we started testing:
- Open terminal input
mongod
node app
Background movie entry page: http://localhost:3000/admin/movie
localhost:3000/index
localhost:3000/admin/list
4.1 Deleting functions and Projects Generate configuration files
Delete using jQuery asynchronous request. To do this, we need to change the project structure and place the contents of the BOWER_Components in a new public file. — One of the bower features we need to use here (you can specify which directory to put bower’s downloads in).
- Create a public folder under the project root directory
- {“directory”: “public/libs”}
- Delete the bower_Components folder
- Re-install bootstrap in terminal:
Bower install [email protected]
- Also modify the bootstrap import path for head.jade by adding /libs
- It is best to change the bower_components in app.js to public. At this point, you can enter the paths again to test.
The test is successful and there is no problem. We continue to add and delete the function, create a new file js under the public file, create admin.js in the js file, write the code:
$(function(){
$(".del").click(function(e){
var target = $(e.target)
var id =target.data('id')
var tr =$('.item-id-'+id)
$.ajax({
type:"DELETE",
url:'/admin/list?id='+id
})
.done(function(results){
if(results.success ===1){
if(tr.length>0){
tr.remove()
}
}
})
})
})
Copy the code
Add code to list.jade
script(src="/js/admin.js")
Copy the code
Add and delete routes in app.js:
//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.send({success:1})
}
})
}
})
Copy the code
Then upload the modified code file to the code cloud:https://gitee.com/ShaoBingYouTiao/movies
Conclusion: The first phase of the website construction strategy has been completed. For many students who are not familiar with Jade, this project may be resistant to writing jade code, but if you follow my above ideas to write it bit by bit, it is still very fruitful. The code in this project is given it is very likely ~ very likely that there are one or two word spelling errors that cause problems when you run the project. At this time, you should carefully check the reason. I have pasted the correct code as much as possible.
About the upgrade project, phase ii study and document finishing I will update as soon as possible, affix address first: phase ii study lesson video mu web address: www.imooc.com/learn/197 phase ii study Jane books document finishing address: www.jianshu.com/p/a91924275…