1. 简单Web服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var http = require("http");
http.createServer(function(req, res) {
var path = req.url.replace(/\/?(?:\?.*)?$/, "").toLowerCase();
switch (path) {
case "":
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("homepage");
break;
case "/about":
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("About");
break;
default:
res.writeHead(404, {'Content-Type': 'text/plain'})
res.end('Not found')
break;
}
}).listen(3000);
console.log('server start 3000')

2. Express框架

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
var express = require("express");
var app = express();

var handlebars = require('express3-handlebars').create({defaultLayout: 'main'})
app.engine('handlebars', handlebars.engine)
app.set('view engine', 'handlebars')

app.use(express.static(__dirname + '/public'))

app.set("port", process.env.PORT || 3000);

app.get("/", function(req, res) {
// res.type("text/plain");
// res.send("Meadowlark Travel");
res.render('home')
});

var fortunes = [
'Conquer your fears or they will conquer you.',
'Rivers need spring',
'Do not fear what you don,t know.',
'You will have a pleasant surprise.',
'whenever possible, keep it simple.'

]
app.get("/about", function(req, res) {
// res.type("text/plain");
// res.send("About Meadowlark Travel");
var randomFortune = fortunes[Math.floor(Math.random() * fortunes.length)];
res.render('about', { fortune: randomFortune})
});
// 定制404页面

app.use(function(req, res, next) {
// res.type("text/plain");
// res.status(404);
// res.send("404 - Not Found");
res.status(404)
res.render('404')
});

app.use(function(err, req, res, next) {
// console.log(err.status);
// res.type("text/plain");
// res.status(500);
// res.send("500 - Server Error");
console.log(err.stack)
res.status(500)
res.render('500')
});


app.listen(app.get("port"), function() {
console.log(
"Express started on http://localhost:" +
app.get("port") +
"; press Ctrl - C to terminate."
);
});

在Express中,路由和中间件的添加顺序至关重要
视图引擎默认会返回text/html的内容类型和200的状态码

3. 测试

单元测试&系统测试

  • 页面测试:测试页面的表示和前端功能 Mocha
  • 跨页测试:从一个页面转到另一个页面的功能测试,涉及多个组件,集成测试 -Zombie.js
  • 逻辑测试:对逻辑进行单元和集成测试,只测Javascript
  • 去毛:找潜在错误 JShint做去毛
  • 链接检查:-LinkCheck

注意:--save-dev告诉npm要把这个包放在开发依赖项中,不要放在运行时依赖项里,这样当我们部署网站的现实实例时,可以减少项目的依赖项。
持续集成(CI)

6. 请求对象

URL组成:协议+主机名+端口+路径+查询字符串+消息片段
请求体:

  • POST请求体最常见的媒体类型是application/x-www-form-urlendcoded,键值对集合的简单编码,用&分割
  • POST请求文件上传,媒体类型是multipart/form-data,一种更为复杂的格式
  • 最后AJAX请求,可以使用application/json