任何根据下面提供的代码解决以下错误的建议将不胜感激,因为我在这里迷路了:
~/public_html/server/routes/api.js:10
api.use(function(req, res, next){
^
TypeError: Cannot call method 'use' of undefined
at Object.<anonymous> (~/public_html/server/routes/api.js:10:5)
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> (~/public_html/server/server.js:72:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
首先,这是我的应用程序目录的相关结构:
--public_html
--node_modules
--express
--pg
--body-parser
--server
--routes
api.js
index.js
server.js
我在 server.js 中为我的路线设置了一个基本的 express 应用程序:
// server.js
var express = require('../node_modules/express'),
app = express(),
bodyParser = require('../node_modules/body-parser'),
app.set('port', 3000);
app.use(bodyParser);
app.use('/api', require('./routes/api').api);
app.use('/', require('./routes/index').index);
// Start server
app.listen(app.get('port'), function () {
console.log("listening on port %d in %s mode", app.get('port'), app.settings.env);
});
然后,在我的 api.js 中,我创建路由并定义我必要的 HTTP 动词。我将在这里展示 1 .get 调用:
// api.js
var pg = require('../../node_modules/pg'),
express = require('../../node_modules/express'),
connString = "postgres://db_user:xxxx@localhost:5432/db_name";
var api = express.Router();
api.use(function(req, res, next){
console.log('in api.js...');
next();
});
api.get('getUsers', function(req, res) {
pg.connect(connString, function(err, client, done) {
if (err) {
console.error("Error fetching client from pool", err);
} else {
client.query('SELECT * FROM users',
function(err, result) {
done();
if (err) {
console.error("Error querying database", err);
} else {
res.json(result[0]);
}
});
}
});
});
module.exports.api = api;