Node.js

Express(中间件)

2017-11-24  本文已影响11人  余生筑

中间件种类

app.use(‘/xxx’,(res,req,next)=>{
next()
})
app.use(‘/xxx’,(err,res,req,next)=>{
res.end(err)
})
   localhost:8888/index/               网站首页
   localhost:8888/customer/login 实现用户登录
   localhost:8888/customer/out    实现用户退出登录

可以这么写
app.js

const express = require('express')
const http = require('http')
var app = express()
const bodyParser = require('body-parser')
var index=require('./middlewares/index');
var customer=require('./middlewares/customer');

app.use('/',index)
app.use('/customer',customer)
app.use( function (req, res, next) {
    res.end();
  });

const server = http.createServer(app);

server.listen('8888');

index.js

const express = require('express')
const router = express.Router();

var index = (res, req, next) => {
    console.log('首页')
    next()
}
router.use('/',index);//这里等效于router.use(index);因为'/'等效于''

module.exports = router;

customer.js

const express = require('express')
const router = express.Router();


var login = (res, req, next) => {
    console.log('登录')
    next()
}

var out = (res, req, next) => {
    console.log('退出登录')
    next()
}


router.use('/login',login)
router.use('/out',out)

module.exports = router;
上一篇下一篇

猜你喜欢

热点阅读