1、app.use()和app.METHOD()
两者都有接收req的路径,然后做出下一步 的作用。
当然,use()还有调用中间件等其他的作用,但原理还是接收路径的原理。想详细了解可看官方文档。
app.METHOD()是app.post(),app.get(),app.put()等方法的统称
① app.use(path,callback)
② app.METHOD(path,callback)
两者区别在于,METHOD()的回调只能使用函数,而use()还可以使用router对象等等,如下
var express = require('express');
var app = express();
var index = require('./routes/index');
app.use('/test1',function(req,res,next){
res.send('hello test1');
});
app.get('/test2',function(req,res,next){
res.send('hello test2');
});
app.get('/test3',index); //报错
app.use('/test4',index);
app.use(express.static(__dirname + '/public'));
//使用指定路径的静态文件
无论是app.use()还是app.METHOD()的path参数,都可以用正则表达式来表示,如
// will match paths starting with /abcd, /abbcd, /abbbbbcd and so on
app.use('/ab+cd', function (req, res, next) {
next();
})
// will match paths starting with /abc and /xyz
app.get(/\/abc|\/xyz/, function (req, res, next) {
next();
})
更详细请看官方文档
2、Router()
在实际开发中通常有几十甚至上百的路由,都写在 index.js 既臃肿又不好维护,这时可以使用 express.Router 实现更优雅的路由解决方案。
用法如下:
在routes文件夹中,创建路径文件users.js
const express = require('express')
const router = express.Router()
router.get('/:name', function (req, res) {
res.send('hello, ' + req.params.name)
})
module.exports = router
在主文件app.js中,截取路径并跳转到routes文件夹users中
const express = require('express');
const app = express();
const userRouter = require('./routes/users');
app.use('/users', userRouter);
app.listen(3000);
3、中间件
毋庸置疑,中间件这是在express框架中是最重要的东西。4.0之后的express不会再像express 3.x那样提供一些中间件供使用。而是需要我们自己下载中间件!
中间件下载
下载中间件有两种方法:
①使用npm install xxx -save
②将要下载的中间件添加到package.json文件中,然后npm install
中间件引用
在所需引用的js文件中,
//比如我现在需要http模块
var http = require("http");
...
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});