安装express以及npm使用方法就不介绍了请自行查看相关内容,这里主要讲express使用方法
express 4.x之后就把命令分离出来了,所以还要另外安装express命令。
express-generator命令,安装完命令之后就可以使用命令生成默认项目包了,如:

要想深入还要自己翻译文档:https://github.com/expressjs/express
npm install express //推荐把express项目包安装在本地 npm install express-generator -g //express命令,使用express -e www命令创建项目,其中-e表示ejs,默认是jade
(如果只有node_modules目录可以手动自己输入:express -e www 就能在www目录下生成其他目录和文件了)
bin //要启动express的文件就存在此目录中的www文件
node_modules //在此目录中安装的第三方模块都在这目录里
public //静态目录里面放js、css、图片
routes //路由,就是写后台逻辑代码的地方
views //存放html的模板目录
app.js //配置文件
中文文档参考:
http://www.cnblogs.com/ae6623/p/4433048.html
https://www.zybuluo.com/XiangZhou/note/208532
https://sdeno.com/wp-content/uploads/2016/08/express_api/express.html
http://javascript.ruanyifeng.com/nodejs/express.html
安装好后初步调用express
var express=require('express'); var app=express();
设置静态目录
express 3.x版本里面内置了很多中间件到了4.x express.static是express唯一提供的中间件 例如根目录下有public目录可以设置如下: app.use(express.static('public')); 在public目录下存放style.css、app.js、hello.html、bg.png,就可以直接访问了如: http://localhost:3000/style.css http://localhost:3000/app.js http://localhost:3000/bg.png http://localhost:3000/hello.html
可以设置多个静态目录 app.use(express.static('public')); app.use(express.static('files'));
为静态目录设置虚拟目录,如: app.use('/xuni',express.static('public')); http://localhost:3000/xuni/style.css
创建http应用
原生的nodejs需要我们手动加载http模块和手动创建http.createServer。
如果安装了express就不需要这些了内置已经帮我们创建好了我们只需要
var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('hello world'); }); app.listen(3000);
输入 http://localhost:3000/
创建后台目录admin
网站一般都分为前、后台之分,可以使用代码
到routes目录中复制index.js一份重新命名admin.js
//app.js var admin = require('admin'); admin.use('/admin', admin); //修改admin.js仅对admin目录起作用
app.set()和app.get()存储一些服务器设置
app.set('name','张三'); app.get('name'); //张三
app.use指定某个目录加载中间件
一般用来加载中间件
app.use(function(req,res,next){ //加载中间件默认对整个目录有效 res.send("hello world"); next(); //不加这个后面的app.use就无法加载 }); app.use('/admin',function(req,res,next){ //加载中间件仅对admin目录有效 res.send("hello world"); next(); //不加这个后面的app.use就无法加载 }); app.use(r1, r2); //同一个页面可以加载多个中间件
如果只想某个路由加载指定的中间件就使用如下:
router.get('/index',run1,fn); //index页面加载指定的run1中间件
app.configure这里可以理解为设置初始值
app.configure(function(){
app.set('name','xiaoshi');
});
//等价于如下
app.set('name','xiaoshi');
//---------------------------------
//---------------------------------
app.configure('development',function(){
app.set('name','xiaoshi');
});
//等价于如下
if('development' == app.get('env')){
app.set('name','xiaoshi');
}
.route(path) //链式写法
var express=require('express');
var router=express.Router();
router.get('/index',[run1,run2],function(req,res,next){ //红色部分此路由加载指定的中间件
//代码
})
.post('/index',function(req,res,next){
//代码
});
修改IP地址
app.set('trust proxy', 'loopback, 123.123.123.123')
路径区分大小写
//在需要启动的模块修改即可 var router = express.Router({caseSensitive: true}); 启动后 /Foo /foo 分别是两个路径,如果不启动不管大小写默认都是/foo
req服务器接收客户端发来的数据
req.setEncoding(“utf8”); //原生,用户提交的数据设置为utf8
req.body.name //获取post方式input name=”name”发来的数据
req.params.name //获取get方式提交的数据 或者req.params[0]
req.query.name //获取get提交的数据
req.cookies //参考《nodejs设置获取cookies案例》
req.fresh / req.stale
req.hostname // localhost
req.originalUrl // 获取当前的页面,如:/index、/home ,如果有参数/login/chenge/age 等于 /login?name=chenge&age=24
req.path // /login/chenge/age 等于 /login?name=chenge&age=24
req.baseUrl //查看当前的路由作用的是哪个目录
req.route //输出当前路由的信息,如:
{ path:"/user/:id?" stack: [ { handle:[Function:userIdHandler], name:"userIdHandler", params:undefined, path:undefined, keys:[], regexp:/^\/?$/i, method:'get' } ] methods:{get:true} }
res客户到收到服务端发来的数据
res.writeHead(200,{‘Content-Type’:’text/plain’}); //原生nodejs,设置http响应头信息
res.type(); //设置http响应头部的信息,如:res.type(‘text/html’) text/plain application/json
res.set(‘Content-Type’,’text/plain’) //效果等同于 res.type(‘text/plain’)
res.get(‘Content-Type’); //获取http响应头信息类型 text/html text/plain application/json
res.send(‘内容’) //直接输出到浏览器上
res.cookie //在客户端创建cookies
res.end(); //结束响应
res.redirect(‘/foo/bar’); //页面跳转
res.redirect(‘http://example.com’);
res.render(‘index’, function(err, html) { //将数据插入到html中
res.send(html);
});
app.get(‘/employee/:uid/:age’, function(req, res, next){
res.json(req.params); // 比如:/111/30,返回 {“uid”: 111, “age”: 30}
});
中间件
可以理解为function封装好的功能。作用是当用户提交数据给服务器的过程中要通过中间件的过滤处理才能提交到服务器中。
// a.js 一个简单中间件 var run = function(){ return function(req,res,next){ //逻辑代码 } next() //如果这里不写这个,那么程序就会执行到没有next()的中间件就停止 } module.exports=run;
调用:
var a=require('a'); 在需要的地方调用即可。 app.use('/',a()); //对整个目录起作用 router.get('/index',a(),fn);
参数、路径(支持正则)
http://localhost:3000/30 设置:/:id? 调用:req.param('id') 输出:30
http://localhost:3000/30/chenge 设置:/:id/:name? 调用:req.param('id') req.param('name') 输出:30 chenge
http://localhost:3000/123/dfsdf%20?%^&*()_ 设置:/* 使用通配符,页面不管输入什么都够正常访问
制作404、500页面
//404和500都要放在所有逻辑代码的最下面 app.use(function(err,req,res,next){ //一定要传入err参数,有页面但是抛出错误就执行这里 console.log(888888+err.message); res.send('500服务器错误'); }); app.use(function(req,res,next){ //一定不能加err参数,无页面执行这里 res.send('404'); });