Web 模块
Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序.
创建 Web 服务器
var http = require('http');
var fs = require('fs');
var url = require('url');
// 创建服务器
http.createServer( function (request, response) {
// 解析请求,包括文件名
var pathname = url.parse(request.url).pathname;
// 输出请求的文件名
console.log("Request for " + pathname + " received.");
// 从文件系统中读取请求的文件内容
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP 状态码: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
// HTTP 状态码: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// 响应文件内容
response.write(data.toString());
}
// 发送响应数据
response.end();
});
}).listen(8081);
// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:8081/');
在该目录下创建一个 index.html 文件
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
创建 Web 客户端
var http = require('http');
// 用于请求的选项
var options = {
host: 'localhost',
port: '8081',
path: '/index.html'
};
// 处理响应的回调函数
var callback = function(response){
// 不断更新数据
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
// 数据接收完成
console.log(body);
});
}
// 向服务端发送请求
var req = http.request(options, callback);
req.end();
(需要先执行server.js)
执行http.request() 最后必须执行 end() 来表明结束了请求事件。
Express 框架
使用 Express 可以快速地搭建一个完整功能的网站。
安装 Express
在命令行通过npm进行安装
npm install express --save
//需要与 express 框架一起安装的
npm install body-parser --save
npm install cookie-parser --save
npm install multer --save
以上命令会将 Express 框架安装在当前目录的 node_modules 目录中。
示例
var express = require('express');
var app = express();
// 主页输出 "Hello World"
app.get('/', function (req, res) {
console.log("主页 GET 请求");
res.send('Hello GET');
})
// POST 请求
app.post('/', function (req, res) {
console.log("主页 POST 请求");
res.send('Hello POST');
})
// /del_user 页面响应
app.get('/del_user', function (req, res) {
console.log("/del_user 响应 DELETE 请求");
res.send('删除页面');
})
// /list_user 页面 GET 请求
app.get('/list_user', function (req, res) {
console.log("/list_user GET 请求");
res.send('用户列表页面');
})
// 对页面 abcd, abxcd, ab123cd, 等响应 GET 请求
app.get('/ab*cd', function(req, res) {
console.log("/ab*cd GET 请求");
res.send('正则匹配');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("应用实例,访问地址为 http://%s:%s", host, port)
})
访问http://127.0.0.1:8081(或者localhost:8081)的不同地址
请求和相应
例如上述代码中
app.get('/', function (req, res) {
console.log("主页 GET 请求");
res.send('Hello GET');
})
使用回调函数的参数: request 和 response 对象来处理请求和响应的数据。
request 对象表示 HTTP 请求,包含了请求查询字符串,参数,内容,HTTP 头部等属性。
response 对象表示 HTTP 响应,即在接收到请求时向客户端发送的 HTTP 响应数据。
路由
通过路由提取出请求的URL以及GET/POST参数。上例中的不同地址,带入了不同的参数,实现路由。
静态文件
express.static 来设置静态文件,如:图片, CSS, JavaScript 等。
app.use(express.static('public'));
表示使用public 目录下的文件。注意这样写时,public文件夹和node_modules在同一级。
GET
<html>
<body>
<form action="http://127.0.0.1:8081/process_get" method="GET">
First Name: <input type="text" name="first_name"> </br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
作为表单输入页面。
var express = require('express');
var app = express();
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.get('/process_get', function (req, res) {
// 输出 JSON 格式
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
})
首先读取index.htm,显示表单页面。提交至process_get页面,在此页面中输出用户输入的内容,由于是GET方法,请求跟在URL后,使用req.query获取URL的查询参数串。
POST
由于参数不附于URL后,需要引入body-parser模块
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/process_post', urlencodedParser, function (req, res) {
// 输出 JSON 格式
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
与GET提取URL参数不同的地方是,POST中需使用req.body 获得请求主体。
COOKIE管理
以下代码输出了客户端发送的 cookie 信息
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8081)
飞呀飞呀