我想将某个模块导出到我的应用程序中.js并使用它。但我发现了一个例外,例如:
'getUserFromDB is not defined'
所以,这就是我的应用程序.js:
var api = require('./routes/API')
app.use(api.router)
和 API .js:
const router = require('express').Router()
function getUserFromDB(login){
// some actions
}
router.get('/get-db', (req, res) => {
getUserFromDB('abcde123')
})
module.exports = {
router: router,
getUserFromDB: getUserFromDB
}
全栈跟踪:
Trace: Trace before app.use(api.router)
at Object.<anonymous> (my-projectbuilddev-server.js:74:9)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:502:3
ReferenceError: getUserFromDB is not defined
at NativeConnection.<anonymous> (my-projectbuilddev-server.js:65:5)
at NativeConnection.g (events.js:292:16)
at emitNone (events.js:86:13)
at NativeConnection.emit (events.js:185:7)
at open (my-projectnode_modulesmongooselibconnection.js:686:11)
at NativeConnection.Connection.onOpen (my-projectnode_modulesmongooselibconnection.js:695:5)
at my-projectnode_modulesmongooselibconnection.js:655:11
at my-projectnode_modulesmongooselibdriversnode-mongodb-nativeconnection.js:71:5
at my-projectnode_modulesmongodblibdb.js:238:5
at Server.connectHandler (my-projectnode_modulesmongodblibserver.js:324:7)
at Server.g (events.js:292:16)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at my-projectnode_modulesmongodb-corelibtopologiesserver.js:300:14
at my-projectnode_modulesmongodb-corelibconnectionpool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
my-projectnode_modulesmongodblibserver.js:327
process.nextTick(function() { throw err; })
我不知道该怎么办。
请尝试以下操作
const router = require('express').Router()
function getUserFromDB(login){
// some actions
return login;
}
router.get('/get-db', (req, res) => {
res.send(getUserFromDB('abcde123'));
})
module.exports = {
router: router,
getUserFromDB: getUserFromDB
}
在应用中更改为以下内容.js
app.use('/', api.router);
const router = require('express').Router()
const getUserFromDB = function(login){
// some actions
}
router.get('/get-db', (req, res) => {
getUserFromDB('abcde123')
})
module.exports = {
router: router,
getUserFromDB: getUserFromDB
}