乐趣区

关于前端:node-框架-express-中-router-的使用

形容

 应用 express.Router 类来创立可装置的模块化路由处理程序。Router 实例是残缺的中间件和路由零碎;因而,经常将其称为“微型应用程序”。以下示例将路由器创立为模块,在其中装入中间件,定义一些路由,而后装置在主应用程序的门路中。在应用程序目录中创立名为 user.js 的路由器文件,其中蕴含以下内容:

我的项目目录

我的项目中应用

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;
退出移动版