描述

使用 express.Router 类来创建可安装的模块化路由处理程序。
Router 实例是完整的中间件和路由系统;因此,常常将其称为“微型应用程序”。
以下示例将路由器创建为模块,在其中装入中间件,定义一些路由,然后安装在主应用程序的路径中。
在应用程序目录中创建名为 user.js 的路由器文件,其中包含以下内容:

项目目录

image.png

项目中使用

app.js

const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const cookieSession = require('cookie-session');

const apiRoutes = require('./routes/api');

const cors = require('cors');
const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(
  cookieSession({
    name: 'session',
    secret: 'sdfasd@d34sdf@',
    maxAge: 24 * 60 * 60 * 1000 * 7,
  })
);
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));

// 相当于拼接路径
app.use('/api', apiRoutes);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.all('*', function (req, res, next) {
  // 相当于域名白名单, 不能写 * ,因为*是通配符 所有网站都可以访问 自己为了玩 用着 也行
  // 不是本公司网站也能访问 ,那就扯了
  // res.setHeader('Access-Control-Allow-Origin', '*');
  // 所以可以单独配置白名单,也就是能进行跨域访问的网址
  res.setHeader('Access-Control-Allow-Origin', ['http://127.0.0.1:8000']);

  //...Headers必须的固定值,"content-type"
  res.setHeader('Access-Control-Allow-Headers', 'X-request-With,content-type');
  // res.setHeader("Access-Control-Allow-Headers","X-request-With");

  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE,PUT,OPTIONS');

  // 放行/下一步 不能省
  next();
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

routes/api.js

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

const userController = require('../controllers/user.js');
const testController = require('../controllers/test.js');

/* 添加用户列表 */
router.post('/user', userController.add);
router.post('/test', testController.add);

module.exports = router;

controllers/user.js

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

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});

// define the about route
router.post('/user', function(req, res) {
  res.send('用户列表api');
});

// define the home page route
router.post('/test', function(req, res) {
  res.send('测试api');
});

module.exports = router;

models/user.js

const mongoose = require('../utils/database.js');

const User = mongoose.model('user', {
  age: Number,
  email: String,
});

module.exports = {
  add(age, email, cb) {
    const user = new User({
      age: age,
      email: email,
    });
    user.save((err) => cb(err));
  },
};

utils/database.js

const mongoose = require('mongoose');
// mongoose.connect('mongodb://数据库路径(包括端口)/数据库名字');
mongoose.connect('mongodb://127.0.0.1:27017/xveZhi');
mongoose.Promise = global.Promise;

module.exports = mongoose;

Tom_Li
26 声望1 粉丝

热爱学习,热爱总结,热爱广博知识