本人是nodejs新人,问题可能比较低级,请多多指教
我用express构造了一个web app,在app.js里定义了如下:
…
exports.test = function() { console.log(“test”); } …
注:我已经查过app.js里,只有这一处exports,并没有module.exports语句.
然后在routes目录下的index.js文件最开始做如下调用: var app = require(‘…/app’).test();
后台抛错:
F:\WorkSpace\ForEveryone\sup\routes\index.js:7 var app = require(‘…/app’).test(); ^ TypeError: Object #<Object> has no method ‘test’ at Object.<anonymous> (F:\WorkSpace\ForEveryone\sup\routes\index.js:7:29) at Module._compile (module.js:456:26) at Object.Module._extensions…js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Module.require (module.js:364:17) at require (module.js:380:17) at Object.<anonymous> (F:\WorkSpace\ForEveryone\sup\app.js:5:14) at Module._compile (module.js:456:26) at Object.Module._extensions…js (module.js:474:10) DEBUG: crashing child
node.js:728 throw errnoException(process._errno, ‘kill’); ^ Error: kill ESRCH at errnoException (node.js:540:13) at process.kill (node.js:728:15) at null._onTimeout (C:\Users\admin\AppData\Roaming\npm\node_modules\supervisor\lib\supervisor.js:252:15) at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
请问我哪里错了,是不是index.js不能调用app.js里的exports方法呢?
我交叉测试了一下。没有问题。Below is code
app.js
exports.testFunc = function()
{
console.log("test");
}
var testFun =require('./routes/index.js');
app.get('/test', function(req, res) {
testFun.test();
});
index.js
appTest = require('../app.js');
exports.test = function()
{
appTest.testFunc();
}
##可以不用这样的,在app.js里面直接定义方法或者变量,在router/xxx.js里面可以直接使用的,如
app.js里面
var mysql = require('mysql');
var app = express();
appPool = mysql.createPool({
host : '127.0.0.1',
user : 'root',
password : 'admin',
port : '8889',
database : 'database1024'
});
在router/index.js里面
exports.index = function(req, res){
appPool.getConnection(function(err, connection) {
connection.query( 'SELECT * FROM user', function(err, rows) {
if (err) throw err;
console.log(rows);
});
connection.release();
res.json('index'+ resultData);
});
}
对JS不太熟,但是这样我测试通过