将var导出到路由文件expressjs [英] export var to routes files expressjs
问题描述
我对来自PHP的nodejs + expressjs完全陌生,并且在如何将var导出/包含到我的route/users.js文件中时遇到了麻烦.
I'm completely new to nodejs + expressjs comming from php and I'm getting trouble how to export/include a var to my routes/users.js file.
在app.js上,我有:
on app.js I have:
//database connection
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbNodeExpress'
});
...一些代码
var user = require('./routes/user');
//这里我包含了我的路由/文件(我不知道在这里添加路由是否正确-出于学习目的现在可以使用
var user = require('./routes/user');
//here I include my routes/files (I dont know if it's right to include the routes here - for learning purposes it works for now)
...更多代码,直到启动服务器
... more code until starts the server
在我的/routes/user.js
On my /routes/user.js
app = require('../app');
//var mysql = require('mysql');
var baseUrl = app.get('baseUrl');
app.get('/users_mysql', function(req, res){
connection.query('SELECT * FROM users', function(err, users){
res.json(users);
});
});
我得到明确的错误:500 ReferenceError:未定义连接
and I get the express error: 500 ReferenceError: connection is not defined
该连接之所以有效,是因为如果我将内容从users.js移到app.js,则可以查询数据库.
The connection works because if I move the content from users.js to app.js I can query the database.
我的问题是如何注入要在route/users.js上使用的var连接
My questions is how to inject the var connection to be used on routes/users.js
任何帮助/提示,以了解这一点非常感谢.预先感谢.
Any help / hint to understand this is very appreciated. Thanks in advance.
推荐答案
有几种方法可以做到这一点.几个解决方案可能是:
There are several ways you could do this. A couple solutions might be:
-
创建一个用于创建和导出连接的resources.js文件.然后在您需要的每个源文件中使用require()resources.js.
Create a resources.js file that creates and exports the connection. Then require() resources.js in every source file where you need it.
将连接传递到您的用户路由文件.像这样的东西:
Pass the connection to your user route file. Something like this:
// app.js
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbNodeExpress'
});
require('./routes/user')(connection);
// routes/user.js
module.exports = function(connection) {
app.get('/users_mysql', function(req, res){
connection.query('SELECT * FROM users', function(err, users){
res.json(users);
});
});
};
这篇关于将var导出到路由文件expressjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!