美文网首页
express路由,mongoose,koa-router写法模

express路由,mongoose,koa-router写法模

作者: 随风飞2019 | 来源:发表于2019-08-15 09:33 被阅读0次

    app里面引入两个路由文件,并声明使用

    var categoryRouter = require('./routes/category.js');
    var userRouter = require('./routes/user.js');
    
    app.use('/api/category', categoryRouter);
    app.use('/api/user', userRouter);
    

    express路由写法
    定义两个路由文件
    第一个category.js

    var express = require('express');
    var router = express.Router();
    
    router.get('/', function(req, res, next) {
      res.send("this is category root")
    });
    
    router.get('/list', function(req, res, next) {
      res.send("this is list")
    });
    
    router.get('/add', function(req, res, next) {
      res.send("this is add")
    });
    
    module.exports = router;
    

    第二个user.js

    var express = require('express');
    var router = express.Router();
    
    router.get('/', function(req, res, next) {
      res.send("this is user root")
    });
    
    router.get('/reg', function(req, res, next) {
      res.send("this is user reg")
    });
    
    module.exports = router;
    

    下面是数据库模型的引入写法
    首先创建一个db.js文件,引入mongoose,写模型,然后导出

    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/epresstoken');
    
    var userSchema = new mongoose.Schema({
        name: String,
        age: Number
    })      
    var userModel = mongoose.model('userModel', userSchema, 'user');
    
    
    var articalSchema=new mongoose.Schema({
        title:String,
        author:String
    })
    var articalModel=mongoose.model("articalModel",articalSchema,"artical");
    
    module.exports={userModel,articalModel}
    

    接着,在路由文件里引入模型,用来使用

    var express = require('express');
    var router = express.Router();
    
    var {userModel} = require("../db.js");
    //引入模型
    
    router.get('/reg', function(req, res, next) {
      let temp=new userModel({name:"zyw",age:32});
      temp.save()
    });
    
    module.exports = router;
    
    koa写法
    首先app里面这样写,注意顺序
    const Koa = require("koa");
    const app=new Koa();
    
    const cors = require('koa2-cors');
    app.use(cors());
    
    const bodyParser = require('koa-bodyparser');
    app.use(bodyParser());
    
    const reg = require('./routes/reg.js')
    app.use(reg.routes(), reg.allowedMethods())
    
    app.listen(3000)
    然后写路由,在./routes/下面新建一个reg.js
    const router = require('koa-router')();
    
    router.post('/reg', async (ctx, next)=> {
        ctx.body = ctx.request.body;
    })
    
    module.exports = router
    这样一个koa路由api就搭建好了
    

    相关文章

      网友评论

          本文标题:express路由,mongoose,koa-router写法模

          本文链接:https://www.haomeiwen.com/subject/todajctx.html