Home >Web Front-end >JS Tutorial >NodeJS creates a basic application and applies the template engine_node.js

NodeJS creates a basic application and applies the template engine_node.js

WBOY
WBOYOriginal
2016-05-16 15:05:471868browse

The purpose of this time is to build a most basic NodeJS server that can realize functions and reflect the workflow of NodeJS and the basic framework of development.
Requirements: nodejs and express have been installed.
1. Build a basic NodeJS server (express, routing)

var express = require(‘express'); //引入express模块 
var app = express(); //调用express()函数,对函数进行初始化 
app.get('/stooges/:name?', function(req, res, next){ //设置第一个路由,期待一个name被输入 
 var name = req.params.name; //获取输入的名字,req.params 
 switch(name?name.toLowerCase():' '){ //对名字进行判断 
 case ‘larry': 
 case ‘curly': 
 case ‘moe': 
  res.send(name + 'is my favorite stooge.'); //符合条件利用res.send发送信息 
 break; 
 default:  
  next(); //next()函数,在function中也有参数传递,它的含义是如果这个路由传递的参数不够不能执行这个路由的话,next()函数表示跳转到下一个函数继续执行(这里是路由) 
} 
}); 
app.get(‘/stooges/*?', function(){ //这里?表示最后的参数可以有也可以没有,同上一个路由相同 
 res.send(‘no stooges listed'); 
}); 
app.get(‘/?', function(req,res){ //什么都没有的时候默认的路由 
 res.send(‘hello world'); 
}); 
var port = 8080; //设定并对端口进行监听 
app.listen(port); 
console.log(‘Listensing on port' + port); 

2. Use Jade template engine and add template rendering

var express = require(‘express'); 
var app = express(); 
//下面三句话完成了对view的设定,包括引擎、模板路径以及其他设定 
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}); //进行视图的渲染,传入模板名即可 
 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 stooges.jade. The codes of the three template files are as follows:
layout.jade

!!! 5 //代表文档类型是HTML5
html(lang=”en”)
head
 title My Web Site
 block scripts
block content
 

index.jade

entends layout
block content
hi hello world
 

stooges.jade

extends layout
block content
if(stooge)
 p #{stooge} is my favorite stooge. //这里的#{stooge}获取了js渲染模板时传递进来的参数
Else
 p no stooges listed 

With the above code, you can use node.js and express to build a basic node application.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn