1. Set up CREATE DATABASE Package.json
{"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"}}
Database configuration:
{"host": "localhost", "User": "Root", "database": "Cart_example"}
Running the database startup code will complete the initial creation of the database, because MySQL and MongoDB are different
var mysql = require (' mysql '), config = require ('./config ');d elete Config.database;var db = mysql.createconnection (config );//Connect Database Db.on (' ERROR ', function () {}),//console.log (db);d b.query (' CREATE DATABASE IF not EXISTS ' cart_example ');// Create Database Db.query (' use ' cart_example '),//Using Database Db.query (' DROP table IF EXITS item ');//delete Table Db.query (' CREATE table item (' +// CREATE TABLE ' ID INT (one) auto_increment, ' + ' title VARCHAR (255), ' + ' description TEXT, ' + ' created DATETIME, ' + ' PRIMARY KEY (ID) ');d b . query (' DROP table IF EXITS review ');//delete Table Db.query (' CREATE Table review (' +//creates table ' ID INT (one) auto_increment, ' + ' item_id in T (one), ' + ' text text, ' + ' stars INT (1), ' + ' created DATETIME, ' + ' PRIMARY KEY (ID)) ');d b.end (function () {process.exit ();});
2. Server code
<pre name= "Code" class= "JavaScript" >var Express = require (' Express '); var session = require (' express-session ');// Before is included in Express, now independent out var bodyparser = require (' Body-parser ');//Before is included in Express, now independent out var mysql = require (' mysql '); MySQL drive var config = require ('./config '); var app = Express ();//app.use ({secret: ' My Secret ', Resave:false, Saveuninitialized:true})); App.use (bodyparser.urlencoded ({extended:true}));//Only This is true to correctly parse out the members of the post message App.use ( Bodyparser.json ());//Handle the parameters from the client and store it in Req.body.user app.use (express.static (' views '));//Prevent the client resource's folder App.set (' view Engine ', ' jade ');//Set HTML parsing engine is Jadeapp.set (' view options ', {layout:false});//var db = mysql.createconnection (config) ;//Connect MySQL database//app.get ('/', function (req,res,next) {//home page Getconsole.log ('---------------/------------------'); Db.query (' SELECT id,title,description from item ', function (err,results) {//Find all Items console.log ('--------------------- ---get "/" '); Console.log (results); Res.render (' index ', {items:results});//items are passed as parameters to the home page}); App.post('/create ', function (req,res,next) {//Create item Postconsole.log ('---------------/create------------------');d b.query (' INSERT INTO item SET title=?,description=? ',//Inserts a newly created item [Req.body.title,req.body.description],function (Err,info) {/ /[] To prevent SQL injection attacks if (ERR) return next (Err), Console.log ('-item created with ID%s ', info.insertid); Res.redirect ('/ ');//relocate to the homepage so that items will appear immediately}); App.get ('/item/:id ', function (req,res,next) {//Select the Get path of the item Console.log ('---------------/item/: ID------------------'), function GetItem (FN) {//Find item Db.query from database (' SELECT id,title,description from item WHERE id=? LIMIT 1 ',//find the corresponding ID of the item [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) {//Get the evaluation information of the item db.query (' SELECT text,stars from review WHERE item_id =? ',//Read database [item_id], function (err,results) {if (err) {return next (err);} fn (results);//Return All evaluation information}); GetItem (function (item) {//Get 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});//reposition page, pass item, and Review});}); App.post ('/item/:id/review ', function (req,res,next) {//Evaluation Item Routing Console.log ('---------------/item/:id/ Review------------------');d b.query (' INSERT INTO review SET item_id=?,stars=?,text=? ',//Insert evaluation information [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);//relocate to the item page so that the evaluation information can be displayed}); App.listen (3000,function () {console.log ('-listining on http://*:3000 ');});
3. client file A.
DOCTYPE Htmlhtmlheadtitle My shopping cartbodyh1 my shopping cart#cartblock body
B.index
Extends./layoutblock bodyh2 all Itemsif (items.length) Uleach item in itemslih3:a (href = "/item/#{item.id}") = Item.title= Item.descriptionelsep No items to showh2 Create new Itemform (action= "/create", method= "POST") Plabel titleinput (type= " Text ", name=" title ") Plabel Descriptiontextarea (name=" description ") Pbutton Submit
C.item
Extends./layoutblock Bodya (href= "/") Go backh2= item.titlep= item.descriptionh3 User reviewsif (reviews.length) each Review in Reviews.reviewb #{review.stars} starsp= review.texthrelsep No reviews to show. Write one!form (action= "/item/#{item.id}/review", method= "POST") fieldsetlegend Create Reviewplabel starsselect (name= "Stars") option 1option 2option 3option 4option 5plabel reviewtextarea (name= "text") Pbutton (type= "Submit") Send
4. Running Results
A. Database status
B. Console
c.index.html Display
d.item.html Display
The source of this example is: "The Great Nodejs"
Nodejs+mysql 1