- Async vs sync
- Hello Express
- Hello world http
- Hello world MongoDB
- Hello world Swig
- Express: handling POST requests
Async vs sync
# Installation npm install mongodb # Run mongo shell example mongo script.js # Run node.js example node app.js //app.js file var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { if(err) throw err; // Find one document in our collection db.collection('coll').findOne({}, function(err, doc) { // Print the result console.dir(doc); // Close the DB db.close(); }); // Declare success console.dir("Called findOne!"); }); //script.js file // Find one document in our collection var doc = db.coll.findOne(); // Print the result printjson(doc);
Hello Express
/app.js var express = require('express') , app = express() // Web framework to handle routing requests , cons = require('consolidate'); // Templating library adapter for Express app.engine('html', cons.swig); app.set('view engine', 'html'); app.set('views', __dirname + '/views'); app.use(app.router); // Handler for internal server errors function errorHandler(err, req, res, next) { console.error(err.message); console.error(err.stack); res.status(500); res.render('error_template', { error: err }); } app.use(errorHandler); app.get('/:name', function(req, res, next) { var name = req.params.name; var getvar1 = req.query.getvar1; var getvar2 = req.query.getvar2; res.render('hello', { name : name, getvar1 : getvar1, getvar2 : getvar2 }); }); app.listen(3000); console.log('Express server listening on port 3000');
<h1>Hello, {{name}}, here are your GET variables:</h1> <ul> <li>{{getvar1}}</li> <li>{{getvar2}}</li> </ul>
var express = require('express'), app = express(); app.get('/', function(req, res){ res.send('Hello World'); }); app.get('*', function(req, res){ res.send('Page Not Found', 404); }); app.listen(8080); console.log('Express server started on port 8080');
Hello world http
// Source: howtonode.org/hello-node // Load the http module to create an http server. var http = require('http'); // Configure our HTTP server to respond with Hello World to all requests. var server = http.createServer(function (request, response) { //response.writeHead(200, {"Content-Type": "text/plain"}); //response.end("Hello World\n"); response.send("Hello World\n"); }); // Listen on port 8000, IP defaults to 127.0.0.1 server.listen(8000); // Put a friendly message on the terminal console.log("Server running at http://127.0.0.1:8000/");
Hello world MongoDB
var MongoClient = require('mongodb').MongoClient; //var Server = require('mongodb').Server; // Examples of two different ways to connect to mongodb //var mongoclient = new MongoClient(new Server("localhost", 27017, {native_parser: true})); //mongoclient.open(function(err, mongoclient) { // console.log("Open!"); //}); // // Open the connection to the server MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { //MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { if(err) throw err; // Find one document in our collection db.collection('coll').findOne({}, function(err, doc) { if(err) throw err; // Print the result. Will print a null if there are no documents in the db. console.dir(doc); // Close the DB db.close(); }); // Declare success console.dir("Called findOne!"); });
Hello world Swig
var express = require('express'), app = express(), cons = require('consolidate'); // Templating library adapter for Express app.engine('html', cons.swig); app.set('view engine', 'html'); app.set('views', __dirname + '/views'); app.get('/', function(req, res){ res.render('hello', { name : 'World' }); }); app.get('*', function(req, res){ res.send('Page Not Found', 404); }); app.listen(8080); console.log('Express server started on port 8080');
hello.html
<h1>Hello, {{name}}!</h1>
Express: handling POST requests
var express = require('express') , app = express() , cons = require('consolidate'); app.engine('html', cons.swig); app.set('view engine', 'html'); app.set('views', __dirname + '/views'); app.use(express.bodyParser()); app.use(app.router); // Handler for internal server errors function errorHandler(err, req, res, next) { console.error(err.message); console.error(err.stack); res.status(500); res.render('error_template', { error: err }); } app.use(errorHandler); app.get('/', function(req, res, next) { res.render('fruitPicker', { 'fruits' : [ 'apple', 'orange', 'banana', 'peach' ] }); }); app.post('/favorite_fruit', function(req, res, next) { var favorite = req.body.fruit; if (typeof favorite == 'undefined') { next(Error('Please choose a fruit!')); } else { res.send("Your favorite fruit is " + favorite); } }); app.listen(3000); console.log('Express server listening on port 3000');
error_template.html
<h1>Error: {{error}}</h1>
fruitPicker.html
<html> <head><title>Fruit Picker</title></head> <body> <form action="/favorite_fruit" method="POST"> <p>What is your favorite fruit?</p> {% for fruit in fruits %} <input type="radio" name="fruit" value="{{fruit}}">{{fruit}}</input> <br/> {% endfor %} <p><input type="submit" value="Submit"/></p> </form> </body> </html>

Leave a Comment