{ "name":"shopping-cart-example" ,"version":"0.0.1" ,"dependencies":{ "express":"4.10.6" ,"express-session":"1.9.3" ,"jade":"1.8.2" ,"body-parser":"1.10.0" ,"mysql":"2.5.4" } }
数据库配置:
{ "host":"localhost", "user":"root", "database":"cart_example" }
var mysql = require('mysql'), config = require('./config'); delete config.database; var db = mysql.createConnection(config);//连接数据库 db.on('error',function(){ }); //console.log(db); db.query('CREATE DATABASE IF NOT EXISTS `cart_example`');//创建数据库 db.query('USE `cart_example`');//使用数据库 db.query('DROP TABLE IF EXITS item');//删除表 db.query('CREATE TABLE item (' + //创建表 'id INT(11) AUTO_INCREMENT,'+ 'title VARCHAR(255),'+ 'description TEXT,'+ 'created DATETIME,' + 'PRIMARY KEY (id) )'); db.query('DROP TABLE IF EXITS review');//删除表 db.query('CREATE TABLE review (' + //创建表 'id INT(11) AUTO_INCREMENT,'+ 'item_id INT(11),'+ 'text TEXT,'+ 'stars INT(1),'+ 'created DATETIME,'+ 'PRIMARY KEY (id) )'); db.end(function(){ process.exit(); });
<pre name="code" class="javascript">var express = require('express'); var session = require('express-session');//之前是包括在express中,现在独立出来 var bodyParser = require('body-parser');//之前是包括在express 中,现在独立出来 var mysql = require('mysql');//mysql 驱动 var config = require('./config'); var app = express();// app.use(session( {secret:'my secret' ,resave:false ,saveUninitialized: true} )); app.use(bodyParser.urlencoded({ extended: true }));//只有这里是true才能正确解析出POST信息中的成员 app.use(bodyParser.json());//处理客户端传来的参数,并且存储在req.body.user中 app.use(express.static('views'));//防止客户端资源的文件夹 app.set('view engine','jade');//设置HTML解析引擎是jade app.set('view options',{layout:false}); // var db = mysql.createConnection(config);//连接mysql数据库 // app.get('/',function(req,res,next){//主页get console.log('---------------/------------------'); db.query('SELECT id,title,description FROM item',function(err,results){//查找所有物品 console.log('------------------------get "/"'); console.log(results); res.render('index',{items:results});//物品作为参数传给主页 }); }); app.post('/create',function(req,res,next){//创建物品post console.log('---------------/create------------------'); db.query('INSERT INTO item SET title=?,description=?',//插入一个新创建的物品 [req.body.title,req.body.description],function(err,info){//[]中的参数替换'?',防止SQL注入攻击 if(err)return next(err); console.log(' - item created with id %s', info.insertId); res.redirect('/');//重新定位到主页,这样物品会立刻显示出来 }); }); app.get('/item/:id',function(req,res,next){//选择物品的get 路径 console.log('---------------/item/:id------------------'); function getItem(fn){//从数据库中找到物品 db.query('SELECT id,title,description FROM item WHERE id=? LIMIT 1',//找到对应id的物品 [req.params.id],function(err,results){ if(err){ return next(err); } if(!results[0]){ return res.send(404); } fn(results[0]); }); } function getReviews(item_id,fn){//获取物品的评价信息 db.query('SELECT text,stars FROM review WHERE item_id = ?',//读数据库 [item_id],function(err,results){ if(err){ return next(err); } fn(results);//返回所有评价信息 }); } getItem(function(item){//获取物品 getReviews(item.id,function(reviews){ console.log('------------getReviews-------------'); console.log('item=') console.log(item); console.log('reviews='); console.log(reviews); res.render('item',{item:item,reviews:reviews});//重新定位页面,并传递物品,和评价 }); }); }); app.post('/item/:id/review',function(req,res,next){//评价物品路由 console.log('---------------/item/:id/review------------------'); db.query('INSERT INTO review SET item_id=?,stars=?,text=?',//插入评价信息 [req.params.id,req.body.stars,req.body.text],function(err,info){ console.log(' - review created with id %s',info.insertId); res.redirect('/item/' + req.params.id);//重新定位到物品页面,这样可以显示评价信息 }); }); app.listen(3000,function(){ console.log(' - listining on http://*:3000'); });
doctype html html head title My shopping cart body h1 My shopping cart #cart block bodyb.index
extends ./layout block body h2 All items if (items.length) ul each item in items li h3: a(href = "/item/#{item.id}")= item.title = item.description else p No items to show h2 Create new item form(action="/create",method="POST") p label Title input(type="text",name="title") p label Description textarea(name="description") p button Submit
extends ./layout block body a(href="/") Go back h2= item.title p= item.description h3 User reviews if(reviews.length) each review in reviews .review b #{review.stars} stars p= review.text hr else p No reviews to show.Write one! form(action="/item/#{item.id}/review",method="POST") fieldset legend Create review p label Stars select(name="stars") option 1 option 2 option 3 option 4 option 5 p label Review textarea(name="text") p button(type="submit") Send
本实例来源为:《了不起的nodejs》
原文地址:http://blog.csdn.net/konglingbin66/article/details/42613121