The purpose of this time is to build a most basic NodeJS server that can implement functions, which can reflect the NodeJS workflow and basic development framework.
Requirements: Nodejs and Express have been installed.
1. Build a basic NodeJS server (express, routing)
var express = require('express'); //Introduce the expression module var app = express(); //Calendar the express() function and initialize the function app.get('/stooges/:name?', function(req, res, next){ //Set the first route and expect a name to be input var name = req.params.name; //Get the input name, req.params switch(name?name.toLowerCase():' '){ //Judge the name case 'larry': case 'curly': case 'moe': res.send(name + 'is my favorite stande.'); //Send information with res.send; default: next(); //next() function also has parameter passing in function. Its meaning is that if the parameters passed by this route are not enough to execute this route, next() function means to jump to the next function to continue execution (here is the route) } }); app.get('/stooges/*?', function(){ //Here? means that the last parameter can be or not, the same as the previous route is res.send('no standes listed'); }); app.get('/?', function(req,res){ //The default route res.send('hello world'); }); var port = 8080; //Set and listen to the port app.listen(port); console.log('Listensing on port' + port);2. Use the Jade template engine to add template rendering
var expression = require('express'); var app = express(); //The following three sentences complete the setting of the view, including the engine, template path and other settings app.set('view engine', 'jade'); app.set('view options', {layout:true}); app.set('views', __dirname + '/views'); app.get('/stooges/:name?', function(req, res, next){ var name = req.params.name; switch(name?name.toLowerCase():' '){ case 'larry': case 'curly': case 'moe': res.render('stooges', {stooge: name}); //Resource the view and pass in the template name to break; default: next(); } }); app.get('/stooges/*?', function(req, res){ res.render('stooges', {stooges:null}); }); app.get('/?', function(req, res){ res.render('index'); }); var port = 8080; app.listen(port); console.log('Listensing on port' + port);There are three template files in total, namely layout.jade (layout file), index.jade and standes.jade. The three template files codes are as follows:
layout.jade
!!! 5 //Represents the document type is HTML5html(lang=”en”)head title My Web Site block scriptsblock content
index.jade
entends layoutblock contenthi hello world
standes.jade
extends layoutblock contentif(stooge) p #{stooge} is my favorite standoge. //The #{stooge} here gets the parameters passed in when rendering the template by JS Else p no standoges listedThrough the above code, you can use node.js and express to build a basic node application.