Express 是一个简洁而灵活的 node.js Web应用框架,使用 Express 可以快速地搭建一个完整功能的网站。
1、Express 框架核心特性:
① 可以设置中间件来响应 HTTP 请求。
② 定义了路由表用于执行不同的 HTTP 请求动作。
③ 可以通过向模板传递参数来动态渲染 HTML 页面。
2、Express安装:
① 本地安装:npm install express
② 全局安装:npm install express -g
3、请求与响应:
Express 框架使用回调函数的参数——Request 和 Response 对象来处理请求和响应的数据。
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("应用实例,访问地址为 http://%s:%s", host, port);
});
运行方式:node express.js
在浏览器中访问:http://127.0.0.1:8081
4、路由:
路由决定了由谁(指定脚本)去响应客户端请求。在HTTP请求中,可以通过路由提取出请求的URL以及GET/POST参数。
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)
});
5、静态文件:
Express 提供了内置的中间件 express.static 来设置静态文件如:图片、CSS、JavaScript 等。
可以使用 express.static 中间件来设置静态文件路径,如app.use(express.static('public'))将图片、CSS、JavaScript文件放在 public 目录下。
6、GET方法:
get.html:
<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>
get.js:
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/get.html', function (req, res) {
res.sendFile( __dirname + "/" + "get.html" );
});
app.get('/process_get', function (req, res) {
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("应用实例,访问地址为 http://%s:%s", host, port);
});
运行方式:node get.js
在浏览器中访问:http://127.0.0.1:8081/get.html
7、POST方法:
post.html:
<html>
<body>
<form action="http://127.0.0.1:8081/process_post" method="POST">
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>
post.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(express.static('public'));
app.get('/post.html', function (req, res) {
res.sendFile( __dirname + "/" + "post.html" );
});
app.post('/process_post', urlencodedParser, function (req, res) {
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("应用实例,访问地址为 http://%s:%s", host, port);
});
运行方式:nodepost.js
在浏览器中访问:http://127.0.0.1:8081/post.html
问题:nodejs 使用require('body-parser')出错。
解决:body-parser已经不和Express绑定在一起了,而需要单独来安装,执行如下命令即可:
npm install body-parser。
8、文件上传:
file.html:
<html>
<body>
<h3>文件上传:</h3>
选择一个文件上传: <br />
<form action="/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="image" size="50" /><br />
<input type="submit" value="上传文件" />
</form>
</body>
</html>
file.js:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}).array('image'));
app.get('/file.html', function (req, res) {
res.sendFile( __dirname + "/" + "file.html" );
});
app.post('/file_upload', function (req, res) {
console.log(req.files[0]);
var des_file = __dirname + "/" + req.files[0].originalname;
fs.readFile( req.files[0].path, function (err, data) {
fs.writeFile(des_file, data, function (err) {
if(err)
console.log( err );
else {
response = {
message:'File uploaded successfully',
filename:req.files[0].originalname
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("应用实例,访问地址为 http://%s:%s", host, port);
});
运行方式:node file.js
在浏览器中访问:http://127.0.0.1:8081/file.html
问题:nodejs 使用require('multer')出错。
解决:multer需要单独来安装,执行如下命令即可:npm install multer。
9、cookie:
cookie.js:
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);
运行方式:node cookie.js
在浏览器中访问:http://127.0.0.1:8081
问题:nodejs 使用require('cookie-parser')出错。
解决:cookie-parser需要单独来安装,执行如下命令即可:npm install cookie-parser。