Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

on app.js I have:

//database connection
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'dbNodeExpress'
});

... some code

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

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);
  });
});

and I get the express error: 500 ReferenceError: connection is not defined

The connection works because if I move the content from users.js to app.js I can query the database.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
271 views
Welcome To Ask or Share your Answers For Others

1 Answer

There are several ways you could do this. A couple solutions might be:

  1. Create a resources.js file that creates and exports the connection. Then require() resources.js in every source file where you need it.

  2. 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);
    });
  });
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...