Answer the question
In order to leave comments, you need to log in
How to export a module in Node.js?
Hello!
There are 2 files (index.js which runs the whole application and func.js).
You need to export the func.js file as a module in index.js.
I am doing this now (everything works), although I understand that this is not true.
Simplified:
index.js
var express = require('express');
var mysql = require('mysql');
var funcs = require('./func');
var app = express();
// DB
var db = mysql.createConnection({
host : 'localhost',
user : 'usr',
password : '123',
database : 'customers'
});
db.connect();
app.use(funcs);
app.get('/customer', function (req, res) {
db.query('SELECT id, name FROM customers WHERE id='+ req.query.id, function(err, row, fields) {
if (!err) {
res.send(row[0]);
}
else {
console.log(err);
}
}
);
});
var express = require('express');
var mysql = require('mysql');
var app = express();
// DB
var db = mysql.createConnection({
host : 'localhost',
user : 'usr',
password : '123',
database : 'customers'
});
db.connect();
module.exports = app;
app.get('/users', function (req, res) {
db.query('SELECT id, name FROM users WHERE id='+ req.query.id, function(err, row, fields) {
if (!err) {
res.send(row[0]);
}
else {
console.log(err);
}
}
);
});
app.get('/users-other', function (req, res) {
db.query('SELECT id, name FROM users_other WHERE id='+ req.query.id, function(err, row, fields) {
if (!err) {
res.send(row[0]);
}
else {
console.log(err);
}
}
);
});
Answer the question
In order to leave comments, you need to log in
I did it on the advice of Vladlen Ultra .
var express = require('express');
var app = express();
require('./func')(app);
app.listen(3000);
app.get('/customer', function (req, res) {
res.send('customers!');
});
module.exports = function (app) {
app.get('/', function (req, res) {
res.send('none!');
});
app.get('/user', function (req, res) {
res.send('users!');
});
app.get('/users', function (req, res) {
res.send('users others!');
});
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question