Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

node.js - export var to routes files expressjs

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...