Nodejs + jquery Mobile build a simple Mobile web (Server index. js)

Source: Internet
Author: User

A simple application of nodejs and jqm builds a simple page that supports CRUD operations. nodejs is used for the server, JQM is used for the front end, And mongodb is used for data storage. The web framework uses expressjs, the database operation plug-in uses mongoose, And the webpage template uses jade. first of all, you must confirm that your system has installed nodejs, mongodb 1. the web framework uses expressJs 3.x. Currently, the latest version is 4. major differences between Version x, the new version and the old version: (the routing design is based on restful, so you can use the lightweight restful server restify) => 4. x removes the binding of functional middleware such as bodyParser and cookieParser and needs to be downloaded separately. 4. version x removes route and adds a new route instance. 4. x remove the configure method to configure the environment and run instance parameters => More can refer to the http://scotch.io/bar-talk/expressjs-4-0-new-features-and-upgrading-from-3-0 2. the database uses mongodb, mongoose for Operation Reference: http://mongoosejs.com/3. the web template uses jade. 4. install various plug-ins: npm install package => example: npm install mongoose 2. copy the code of the organizational structure of the application file |=// views stores the View File (index. jade, layout. jade) +/public stores static files (css, javascript, images, etc.) +/node_modules stores nodejs dependent Libraries (Expressjs, mongoose, etc.) + index. main js file, SERVER + package. copy code 3 to the json configuration file (not used. server index. js 1. database application, use mongoose to copy code => database connection: mongoose. connect ('mongodb: // localhost/fruitdb'); mongoose uses document organization to format data, for example, create data: var Schema = mongoose. schema; var FruitSchema = new Schema ({// field definition title: {type: String, require: true}, content: {type: String, require: true} // +> other field}); // generate the Data Model var FruitModel = mon Goose. model ('fruit', FruitSchema); => the data model is the key to true database operations, and schema is only a document structure. for data query, use find ({option}, callback) or findById. for data storage, use the save (callback) method to copy Code 2. the routing design uses the routing function of expressjs to copy the code and use the get, post, put, and del methods of express to implement CRUD operations. If you use expressjs 4. in Version x, you can still use the http get/post/put/del method, or the expressjs router instance. for details about the router instance reference: http://expressjs.com/4x/api.html#router form parsing can use bodyParser middleware => 3.x app. use (express. bodyPar Ser (); if you want to strengthen and expand the instance, you can add session or cookie function, then you can refer to the middleware list of express: https://github.com/senchalabs/connect#middleware => Create a server and listen: you can directly use the app. listen (port) or use the native http module of nodejs http. createServer (app ). listen (port); copy code 3. server code index. js copy code // => nodejs + jqm example // => by andy var express = require ('express '), // express 3.x mongoose = require ('mongoose '), mongodb = require ('mongodb '), path = require ('path'), SC Hema = mongoose. schema; var app = module. exprots = express. createServer (); // configuration, expressJS 4. x configuration see: // http://scotch.io/bar-talk/expressjs-4-0-new-features-and-upgrading-from-3-0 app. configure (function () {app. set ('view', _ dirname + '/view'); app. set ('view engine ', 'jade'); app. use (express. bodyParser (); app. use (express. methodOverride (); app. use (app. router); app. use (express. static (path. joi N (_ dirname, 'public') ;}); // log to print the request url and request method app. use (function (req, res, next) {console. log ('method: % s, url: % s', req. method, req. url) ;}); // configure the app environment. configure ('development ', function () {app. use (express. errorHandler ({dumpExceptions: true, showStack: true}) ;}); app. configure ('production ', function () {app. use (express. errorHandler () ;}); // ==> db config var ObjectId = mongodb. BSO NPure. objectID; // connect to the fruitdb database mongoose. connect ('mongodb: // localhost/fruitdb'); var db = mongoose. connection; db. on ('error', function (err) {console. log (err) ;}); // model definition var FruitSchema = new Schema ({title: {type: String, require: true}, content: {type: String, require: true} // +> other field}); var FruitModel = mongoose. model ('fruit', FruitSchema); // route app. get ('/', function (req, res, Next) {FruitModel. find ({}, function (err, data) {if (err) return next (err); res. render ('index', {fruits: data}) ;}); // +> Add an app. post ('/fruits', function (req, res, next) {var obj = new FruitModel (); obj. title = req. body. title; obj. content = req. body. content; console. log ("obj: % s", JSON. stringify (obj); obj. save (function (err) {if (err) return next (err); res. json ({code: 1, message: 'success save '}) ;}); // +> Returns all fruit apps. get ('/fruits/list', function (req, res, next) {FruitModel. find ({}, function (err, next) {if (err) return next (err); res. json (data) ;}); // +> View the specified app. get ('/fruits/: id', function (req, res, next) {FruitModel. findById ({_ id: ObjectID (req. params. id)}, function (err, data) {if (err) return next (err); res. json (data) ;}); // +> delete an app. del ('/fruits/: id', function (re Q, res, next) {FruitModel. findById ({_ id: ObjectID (req. params. id)}, function (err, data) {if (err) return next (err); data. remove (function (err) {res. json ({code: 1, message: 'success remove. '});}) // => Update the app. put ('/fruits/: id', function (req, res, next) {FruitModel. update ({_ id: ObjectID (req. params. id) },{ title: req. body. title, content: req. body. content },{ upsert: false, multi: false}, fu Nction (err) {if (err) return next (err); res. json ({code: 1, message: 'success Update'}) ;}); // if (! Moudule. parent) {//} //-> start listen app. listen ('123', function () {console. log ('server has been started. ');});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.