访问节点中的ORM数据后快速回调

麦可

我尝试使用Express 4.14.0(orm 3.1.0 / mySQL)设置JSON API在app.js中,我有:

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var data = require('./model/datamodel');
var api = require('./routes/api');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', api);

module.exports = app;                

我使用datamodel.js设置orm:

var express = require('express');
var orm = require('orm');
var app = express();

app.use(orm.express("mysql://onserver:>2hZ[[email protected]/onserver", {
    define: function (db, models, next) {
        models.person = db.define("person", { 
            name      : String,
            surname   : String,
        } );

        next();
    }   
}));

以及api.js作为实际的api:

var express = require('express');
var router = express.Router();
var app = express();    

router.get('/', function(req, res, next) {
    res.json({ message: 'hoorayDATABASE: undefined! welcome to our api!' });  
});

router.route( "/main" ).post( function( req, res ) { 
    console.log( "MODELS:", req.models );  
            // req.models is undefined
            // I want to access req.models.person.find( ... )
})

module.exports = router;  

我打电话给localhost:3000/main我,收到:

型号:未定义

我需要模型对象来检索数据,但是它是未定义的。为什么?

模具

您正在datamodel.js中定义新应用。您只需var app = express();在应用程序中执行一次,然后将app变量传递给其他模块,以便它们都引用同一实例。

这是可以做到的:

app.js

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

// require the module and pass the `app` to the function it exports
require('./model/datamodel')(app);

app.use('/', require('./routes/api'));

module.exports = app; 

数据模型

var orm = require('orm');

module.exports = function(app) {
    app.use(orm.express("mysql://onserver:>2hZ[[email protected]/onserver", {
        define: function (db, models, next) {
            models.person = db.define("person", { 
                name      : String,
                surname   : String,
            } );

            next();
        }   
    }));
}

api.js

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

router.get('/', function(req, res, next) {
    res.json({ message: 'hoorayDATABASE: undefined! welcome to our api!' });  
});

router.post('/main', function( req, res ) { 
    console.log( "MODELS:", req.models );
})

module.exports = router; 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TOP 榜单

热门标签

归档