运行节点服务器时出现以下错误:
$ node server.js
module.js:339
throw err;
^
Error: Cannot find module './server/routes'
at Function.Module._resolveFilename (module.js:337:15)
at Function.Module._load (module.js:287:25)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object.<anonymous> (C:\Users\attas\documents\github\angular-express-auth\server.js:12:10)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
以下是我的项目结构:
server.js:
var express = require('express'),
jwt = require('express-jwt'),
bodyParser = require('body-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('express-error-handler'),
tokenManager = require('./server/config/token_manager'),
secret = require('./server/config/secret'),
http = require('http'),
path = require('path');
var app = module.exports = express();
app.set('port', process.env.PORT || 3000);
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'app')));
var routes = require('./server/routes');
routes.users = require('./server/routes/users.js');
var env = process.env.NODE_ENV || 'development';
// development only
if (env === 'development') {
app.use(errorHandler());
}
// production only
if (env === 'production') {
// TODO
}
app.all('*', function(req, res, next) {
res.set('Access-Control-Allow-Origin', 'http://localhost');
res.set('Access-Control-Allow-Credentials', true);
res.set('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization');
if ('OPTIONS' == req.method) return res.send(200);
next();
});
/*
Login
*/
app.post('/login', routes.users.login);
app.post('/user/register', routes.users.register);
app.get('/me', routes.users.me);
/*
Logout
*/
app.get('/logout', jwt({secret: secret.secretToken}), routes.users.logout);
process.on('uncaughtException', function(err) {
console.log(err);
});
/**
* Start Server
*/
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
没有收到任何错误
tokenManager = require(&#39; ./ server / config / token_manager&#39;)和 secret = require(&#39; ./ server / config / secret&#39;)
想知道为什么它只能加载./server/routes?
答案 0 :(得分:6)
定义这样的模块时:
var routes = require('./server/routes');
如果index.js
目录中存在./server/routes
文件,则表示您调用./server/routes/index.js
文件。
你不能这样打电话:./server/routes/index.js/users.js.
您应该更新您的用户路由器变量,如下所示:
var routes = require('./server/routes');
var users = require('./server/routes/users');
并在server.js文件中更新用户变量的其他用法,以便您的应用正常运行。
答案 1 :(得分:1)
var routes = require('./server/routes');
服务器/路由是一个目录,而不是一个文件,你的意思是
var routes = require('./server/routes/index');