[关闭]
@mynameiszhangxu 2015-04-13T06:18:56.000000Z 字数 2176 阅读 1876

Express

笔记


Jade

定义页面结构

  1. section#wrapper

编译后是

  1. <section id="wrapper"></section>
  1. section#wrapper.class-name

编译后是

  1. <section id="wrapper" class="class-name"></section>
  1. p
  2. span

编译后是

  1. <p><span></span></p>
  1. h1 Very important heading

编译后是

  1. <h1>Very important heading</h1>
  1. p
  2. | Text can be over
  3. | many lines
  4. | after a pipe symbol

编译后是

  1. <p>Text can be over many lines after a pipe symbol</p>

输出数据

  1. - var foo = bar;

变量设置完成可在以后使用

  1. p I wanna learn to use variables.Foo is #{foo}!

循环

  1. - users = ['Sally', 'Joseph', 'Michael', 'Sanjay']
  2. - each user in users
  3. p=user

编译后是:

  1. <p>Sally</p>
  2. <p>Joseph</p>
  3. <p>Michael</p>
  4. <p>Sanjay</p>

如果使用for关键字,可以这么写:

  1. for user in users
  2. p= user

也可以使用对象进行迭代

  1. - obj = {first_name:'George', surname:'Ornbo'}
  2. - each val, key in obj
  3. li #{key}: #{val}

编译后是

  1. <li>first_name:George</li>
  2. <li>Surname:Ornbo</li>

条件

  1. - awake =false
  2. - if (awake)
  3. p You are awake!Make coffee
  4. - else
  5. p You are sleeping

内联(inline)JavaScript

若想内联 JavaScript 代码,声明一个脚块后,在其中加入 JavaScript 代码即可

  1. script
  2. alert('You can execute inline JavaScript througt jade');

包含

用途:大多数网站都会有在站点的每个页面都重复出现的部分,比如页眉,页脚和边栏

jade 通过include关键字后跟想要包含的模板来支持包含功能

  1. html
  2. bady
  3. include includes/header

上述代码从 views/includes/header.jade 文件中包含代码

路由

添加 Get 路由

  1. app.get('/about', function(req, res){
  2. res.send('HELLO from the about route!');
  3. });

添加 Post 路由

  1. app.post('/',function(req,res){
  2. res.send(req.body);
  3. });
  1. h1= title
  2. p Welcome to #{title}
  3. h2 Form example
  4. form(method='post', action='/')
  5. fieldset
  6. legend Add a user
  7. p
  8. label First name
  9. input(name = 'user[first_name]')
  10. p
  11. label Last name
  12. input(name = 'user[last_name]')
  13. p
  14. input(type = 'submit', value='Save')

在路由器中使用参数

申明一个捕获参数的路由

  1. app.get('/users/:id', function(req, res){
  2. res.send('show content for user id' + req.params.id);
  3. });

数据持久化

将数据写入文件

  1. var fs = require('fs'),
  2. data = "Some data I want to write to a file";
  3. fs.writeFile('file.txt' data function(err){
  4. if(!err){
  5. console.log('Worte data to file.txt');
  6. }else{
  7. throw err;
  8. }
  9. });

从文件中读取数据

  1. var fs = require('fs');
  2. fs.readFile('file.txt' "utf8", function (err,data){
  3. if(!err){
  4. console.log(data);
  5. }else{
  6. throw err;
  7. }
  8. });

读取环境变量

如果设置了环境变量 SOMETHING,只需要一行代码就可以将其读出

  1. var = something = process.env.SOMETHING
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注