1.一些常用的api操作
有时候我们可能要获取用户的ip地址和访问时间:
获取ip地址的处理:req.ip
获取访问时间,这时候我们使用Date创建date对象,把时间获取就可以了,同js操作
我们做一个简单的演示,在更目录下,我们已经做了点击“hello world!”进入hello的处理,我们在
路由 get的“/hello”获取这些内容,并且显示在模板页面,路由修改如下:
app.get('/hello', function(req, res){
var ip=req.ip;
var date=new Date();
var ri=date.getDate()
res.render('hello', { text: '么么哒',ip:ip,ri:ri });
});
app.get('/hello', function(req, res){
var ip=req.ip;
var date=new Date();
var ri=date.getDate()
res.render('hello', { text: '么么哒',ip:ip,ri:ri });
});
hello.ejs如下:
<!DOCTYPE html>
<html>
<head>
<title>hello</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= text %></h1>
<h1><%= ip %></h1>
<h1><%= ri %></h1>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>hello</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= text %></h1>
<h1><%= ip %></h1>
<h1><%= ri %></h1>
</body>
</html>
2.ejs模板引擎,后缀改为.html
我们知道,我们使用的是ejs模板引擎,我们看到页面都是.ejs后缀,其实.ejs文件里面写的就是html标签,既然就是html的标签,我们能不能把.ejs改为.html,毕竟很多人看着是不舒服的,主要也是使用模板的时候要修改后缀名很麻烦的,我们做好的静态页都是.html结束。
我们找到手册设置:
app.js相关部分代码如下
// view engine setup
app.engine('html', require('ejs').renderFile);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
// view engine setup
app.engine('html', require('ejs').renderFile);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
对比之前,加入app.engine的设置和set的显示设置为html
重新启动,运行,效果同之前,不过这时候.html和我们做的html页面肯定是不太一样的,正常html页面是不能解析后台数据的!
3.上传文件的存储
按我们获取客户信息的理解,针对上传文件的获取应该是这样:
req.files获取所有上传表单
req.files.file1获取name叫file1的表单
以为类推......
不过很可惜,express没有这样的处理接口,看来我们只能自己截取(有点难)或者使用第三方模块(窃喜)了!
网上使用较多的,存储上传文件的第三方模块是: formidable
我们修改package.json:
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"express": "~3.4.8",
"static-favicon": "~1.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"ejs": "~0.8.5",
"formidable": "*"
}
}
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"express": "~3.4.8",
"static-favicon": "~1.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"ejs": "~0.8.5",
"formidable": "*"
}
}
我们在项目下执行命令:
npm install
npm install
开始安装 formidable,等待完成即可!
我们在路由文件index.js引用当前模块,index.js代码如下:
var formidable = require('formidable');
var fs = require('fs');
function rout(app){
app.get('/',function(req, res){
res.render('index', { title: 'Express',hello: 'hello world!',arr:[111111,2222,33333,44444] });
});
app.get('/hello', function(req, res){
var ip=req.ip;
var date=new Date();
var ri=date.getDate()
res.render('hello', { text: '么么哒',ip:ip,ri:ri });
});
app.get('/list', function(req, res){
res.render('list', { text: req.query.id });
});
app.get('/login', function(req, res){
res.render('login');
});
app.post('/logincheck', function(req, res){
var user= req.body.user;
var pass= req.body.pass;
if(user=="tom" && pass=="tom"){
res.redirect('/');
}else{
res.redirect('/login');
};
});
};
var formidable = require('formidable');
var fs = require('fs');
function rout(app){
app.get('/',function(req, res){
res.render('index', { title: 'Express',hello: 'hello world!',arr:[111111,2222,33333,44444] });
});
app.get('/hello', function(req, res){
var ip=req.ip;
var date=new Date();
var ri=date.getDate()
res.render('hello', { text: '么么哒',ip:ip,ri:ri });
});
app.get('/list', function(req, res){
res.render('list', { text: req.query.id });
});
app.get('/login', function(req, res){
res.render('login');
});
app.post('/logincheck', function(req, res){
var user= req.body.user;
var pass= req.body.pass;
if(user=="tom" && pass=="tom"){
res.redirect('/');
}else{
res.redirect('/login');
};
});
};
我们针对上传操作创建路由处理,
上传页面,路由加入:
get的“/file”处理,
点击上传,路由加入,
post的“/upfile” 处理。
index.js加入代码如下:
app.get('/file', function(req, res){
res.render('file');
});
app.post('/upfile', function(req, res){
//code
});
app.get('/file', function(req, res){
res.render('file');
});
app.post('/upfile', function(req, res){
//code
});
我们创建file.html,我们上面已经把模板后缀修改。
file.html代码:
<!DOCTYPE html>
<html>
<head>
<title>login</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<form method="post" action="/upfile" enctype="multipart/form-data">
<input type="file" name="file">
<input id="ok" type="submit" value="上传">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>login</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<form method="post" action="/upfile" enctype="multipart/form-data">
<input type="file" name="file">
<input id="ok" type="submit" value="上传">
</form>
</body>
</html>
注意点
- enctype的设置
- input类型为file
下面我们该在路由加入上传存储处理了,修改上传路由操作
app.post('/upfile', function(req, res){
//code
var form = new formidable.IncomingForm();
form.uploadDir = "./upload";
form.parse(req, function(err, fields, files) {
if (err) {
res.redirect('/file');
}
var tmp_path, target_path;
if (files.file.size > 0) { //表示有文件上传
tmp_path = files.file.path;//内存中的文件,当前文件目录
var picType = files.file.name.split(".")[1];//后缀名
//移动目的目录
target_path = './public/images/pic_1.' + picType;
//同步方式移动文件
fs.renameSync(tmp_path, target_path);
}else{
res.redirect('/file');
};
});
});
app.post('/upfile', function(req, res){
//code
var form = new formidable.IncomingForm();
form.uploadDir = "./upload";
form.parse(req, function(err, fields, files) {
if (err) {
res.redirect('/file');
}
var tmp_path, target_path;
if (files.file.size > 0) { //表示有文件上传
tmp_path = files.file.path;//内存中的文件,当前文件目录
var picType = files.file.name.split(".")[1];//后缀名
//移动目的目录
target_path = './public/images/pic_1.' + picType;
//同步方式移动文件
fs.renameSync(tmp_path, target_path);
}else{
res.redirect('/file');
};
});
});
重要操作,我们在app.js同级创建upload文件夹,用来临时存放上传的文件。
我们在file页面上传文件,点击上传,就可以在public/images下看见文件了。
几个重要点:
- formidable的方法创建对象
- 指定临时目录
- 使用解析方法,在回调获取文件组
- 文件组.文件表单name名称获取上传文件
- path属性存放上传文件
- renamesync移动文件,参数1老路径,参数2目的路径,此方法可重命名
关于fs模块的各种方法可以在nodejs的api中查看
4.总结
到这里发生修改的文件:
1.app.js 改变模板引擎的后缀名
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/user');
var app = express();
// view engine setup
app.engine('html', require('ejs').renderFile);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
routes.rout(app);
app.get('/users', users.list);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/user');
var app = express();
// view engine setup
app.engine('html', require('ejs').renderFile);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
routes.rout(app);
app.get('/users', users.list);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
2.index.js 加入文件上传的处理
var formidable = require('formidable');
var fs = require('fs');
function rout(app){
app.get('/',function(req, res){
res.render('index', { title: 'Express',hello: 'hello world!',arr:[111111,2222,33333,44444] });
});
app.get('/hello', function(req, res){
var ip=req.ip;
var date=new Date();
var ri=date.getDate()
res.render('hello', { text: '么么哒',ip:ip,ri:ri });
});
app.get('/list', function(req, res){
res.render('list', { text: req.query.id });
});
app.get('/login', function(req, res){
res.render('login');
});
app.post('/logincheck', function(req, res){
var user= req.body.user;
var pass= req.body.pass;
if(user=="tom" && pass=="tom"){
res.redirect('/');
}else{
res.redirect('/login');
};
});
app.get('/file', function(req, res){
res.render('file');
});
app.post('/upfile', function(req, res){
//code
var form = new formidable.IncomingForm();
form.uploadDir = "./upload";
form.parse(req, function(err, fields, files) {
if (err) {
res.redirect('/file');
}
var tmp_path, target_path;
if (files.file.size > 0) { //表示有文件上传
tmp_path = files.file.path;//内存中的文件,当前文件目录
var picType = files.file.name.split(".")[1];//后缀名
//移动目的目录
target_path = './public/images/pic_1.' + picType;
//同步方式移动文件
fs.renameSync(tmp_path, target_path);
}else{
res.redirect('/file');
};
});
});
};
exports.rout=rout;
var formidable = require('formidable');
var fs = require('fs');
function rout(app){
app.get('/',function(req, res){
res.render('index', { title: 'Express',hello: 'hello world!',arr:[111111,2222,33333,44444] });
});
app.get('/hello', function(req, res){
var ip=req.ip;
var date=new Date();
var ri=date.getDate()
res.render('hello', { text: '么么哒',ip:ip,ri:ri });
});
app.get('/list', function(req, res){
res.render('list', { text: req.query.id });
});
app.get('/login', function(req, res){
res.render('login');
});
app.post('/logincheck', function(req, res){
var user= req.body.user;
var pass= req.body.pass;
if(user=="tom" && pass=="tom"){
res.redirect('/');
}else{
res.redirect('/login');
};
});
app.get('/file', function(req, res){
res.render('file');
});
app.post('/upfile', function(req, res){
//code
var form = new formidable.IncomingForm();
form.uploadDir = "./upload";
form.parse(req, function(err, fields, files) {
if (err) {
res.redirect('/file');
}
var tmp_path, target_path;
if (files.file.size > 0) { //表示有文件上传
tmp_path = files.file.path;//内存中的文件,当前文件目录
var picType = files.file.name.split(".")[1];//后缀名
//移动目的目录
target_path = './public/images/pic_1.' + picType;
//同步方式移动文件
fs.renameSync(tmp_path, target_path);
}else{
res.redirect('/file');
};
});
});
};
exports.rout=rout;
3.package.json 依赖加入formidable
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"express": "~3.4.8",
"static-favicon": "~1.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"ejs": "~0.8.5",
"formidable": "*"
}
}
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"express": "~3.4.8",
"static-favicon": "~1.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"ejs": "~0.8.5",
"formidable": "*"
}
}
4.file.ejs
<!DOCTYPE html>
<html>
<head>
<title>login</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<form method="post" action="/upfile" enctype="multipart/form-data">
<input type="file" name="file">
<input id="ok" type="submit" value="上传">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>login</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<form method="post" action="/upfile" enctype="multipart/form-data">
<input type="file" name="file">
<input id="ok" type="submit" value="上传">
</form>
</body>
</html>
5.ejs后缀改为.html