Node.js浏览器错误无法获取/

时间:2016-07-08 16:10:12

标签: javascript node.js express

我对Node很陌生,我一直在按照教程构建一个简单的服务器,该服务器为一些基本路由提供动态pags,但在运行Error: Cannot GET/后继续获取node server.js并在浏览器上调用localhost:3300。我的路由在外部定义并使用routes.initialise()进行初始化,如下所示:

//routes.js
var home = require('../controllers/home'),
image = require('../controllers/image'),
express = require('express');

module.exports.initialize = function(app, router) {
//var router = express.Router();

router.get('/', home.index);
router.get('/images/:image_id', image.index);
router.post('/images', image.create);
router.post('/images/:image_id/like', image.like);
router.post('/images/:image_id/comment', image.comment);

app.use('/', router);
};

我搜索的范围很广,但没有解决方案。我非常沮丧,需要一些帮助。

我有一个创建服务器的server.js:

//server.js
var express = require('express'), 
config = require('./server/configure'),    
app = express(); 

app.set('port', process.env.PORT || 3300); 
app.set('views', __dirname + '/views');
app = config(app);


var server = app.listen(app.get('port'), function() {    
console.log('Server up: http://localhost:' + app.get('port')); 
});

和配置服务器的configure.js:

//configure.js
var path = require('path'),
routes = require('./routes'),
exphbs = require('express3-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');

module.exports = function(app) {
app.engine('handlebars', exphbs.create({
    defaultLayout: 'main',
    layoutsDir: app.get('views') + '/layouts',
    partialsDir: [app.get('views') + '/partials']
}).engine);

app.set('view engine', 'handlebars');
app.use(morgan('dev'));
app.use(bodyParser({
    uploadDir:path.join(__dirname, 'public/upload/temp')
}));

app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes.initialize(app, new express.Router());

app.use('/public/', express.static(path.join(__dirname, '../public')));

if ('development' === app.get('env')) {
    app.use(errorHandler());
}

return app;
};

还有两个文件,home.jsimage.js,它们应该提供来自configure.js的默认路由:

//home.js
module.exports = {
index: function(req, res) {
    res.send('The home:index controller');
}
};

//image.js
module.exports = {    
index: function(req, res) {        
    res.send('The image:index controller ' + req.params.image_id);    
},

create: function(req, res) {        
    res.send('The image:create POST controller');    
},    

like: function(req, res) {        
    res.send('The image:like POST controller');    
},    

comment: function(req, res) {        
    res.send('The image:comment POST controller');    
} 
};

每当我尝试获取浏览器上的任何链接时,它都会返回Can not GET / error。任何帮助将不胜感激。

非常感谢你:)

1 个答案:

答案 0 :(得分:1)

我实际上已经复制了您的确切代码并且它按预期工作,但坦率地说它有一堆间接和至少一个已弃用的模块。也许你有一个PORT环境变量集,所以应用程序实际上并没有在3300上运行?