我是node.js的新手。我创建了一个名为app.js的文件,并使用express将该代码放入该文件中以切换模板引擎:
//module dependencies
var express = require('express');
routes = require ('./routes');
user = require ('./routes/user');
http= require ('http');
path = require ('path');
var exphbs = require ('express3-handlebars');
var app = express();
//all environement
app.set ('port', process.env.PORT || 3000);
app.set('views', __dirname +'/views');
//app.set('view engine','jade');
app.engine('handlebars',exphbs({defaultLayout :'main'}));
app.set('view engine ','handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname,'public')));
//developpement only
if ('developpement' == app.get('env')){
app.use(express.errorHandler());
}
//app.get('/', routes.index);
//app.get ('/user' , user.list);
app.get('/' , function(req,res) {
res.render('home');
}
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
然后我运行应用程序,我收到此错误:
http.createServer(app).listen(app.get('port'), function(){
^^^^
SyntaxError: Unexpected identifier
at Module._compile (module.js:439:25)
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 Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
此行导致错误:
http.createServer(app).listen(app.get('port'), function(){
答案 0 :(得分:7)
您缺少
中的右括号app.get('/' , function(req,res) {
res.render('home');
}) // <-- the last one
你应该使用一个提供正确的语法高亮和一个代码linter的编辑器 - 比如jshint,它会警告你这件事,并警告你不正确的变量声明:
var onevar = 'value'; // <-- superbad! You just ended this statement!
another = 'val2'; // <-- now this variable leaked into global scope!
// Proper:
var onevar = 'value';
var another = 'val2';
// Also proper:
var onevar = 'value',
another = 'val2';
SyntaxError: Unexpected identifier
总是在您的代码中某处出现错字(或者您尝试执行JavaScript无法理解的操作),并且通常会在之前发生意外标识符。过度简化,它基本上意味着解析器处于某个语句的中间,并且根据语法规则,后面的内容对于该特定情况是不可接受的。
答案 1 :(得分:2)
我认为这不正确:
var express = require('express');
routes = require ('./routes');
user = require ('./routes/user');
http= require ('http');
path = require ('path');
我认为你必须尝试这样的事情:
var express = require('express'),
routes = require ('./routes'),
user = require ('./routes/user'),
http= require ('http'),
path = require ('path');
或者
var express = require('express');
var routes = require ('./routes');
var user = require ('./routes/user');
var http= require ('http');
var path = require ('path');