gpt4 book ai didi

mysql - 在 Node express post回调中访问orm数据

转载 作者:行者123 更新时间:2023-11-29 07:08:48 26 4
gpt4 key购买 nike

我尝试使用 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[RpfCT~!xx@localhost/onserver", {
define: function (db, models, next) {
models.person = db.define("person", {
name : String,
surname : String,
} );

next();
}
}));

以及实际 api 的 api.js:

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,我收到:

MODELS: undefined

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

最佳答案

您正在 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;

数据模型.js

var orm = require('orm');

module.exports = function(app) {
app.use(orm.express("mysql://onserver:>2hZ[RpfCT~!xx@localhost/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;

关于mysql - 在 Node express post回调中访问orm数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40609921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com