【发布时间】:2017-08-09 12:12:07
【问题描述】:
在下面的代码中,为什么res.render('home'); 有效,而res.render('update'); 无效?
这是通过 Node.js、Express 和 Handlebars 运行的。
文件结构
myApp
│
├───app.js
│
├───public
│ │
│ └───scripts
│ buttons.js
│
└───views
│ home.handlebars
│ update.handlebars
│
└───layouts
main.handlebars
app.js
var express = require('express');
var app = express();
app.use(express.static('public'));
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var handlebars = require('express-handlebars').create({defaultLayout:'main'});
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port', 3000);
//*****Routes*************
app.get('/',function(req,res,next){
res.render('home');
});
app.get('/update', function(req,res,next){
res.render('update');
});
app.listen(app.get('port'), function(){
console.log('Express started on http://localhost:' + app.get('port') + '; press Ctrl-C to terminate.');
});
buttons.js
document.addEventListener('DOMContentLoaded', bindButtons);
function bindButtons(){
document.getElementById('Submit').addEventListener('click', sendRequest());
}
function sendRequest() {
var req = new XMLHttpRequest();
req.open('GET', 'http://localhost:3000/update');
req.send();
};
home.handlebars
<h1>Home Page</h1>
<input type="submit" id="Submit">
update.handlebars
<h1>Update Page</h1>
main.handlebars
<!doctype html>
<html>
<head>
<title>Main Page</title>
</head>
<body>
{{{body}}}
</body>
</html>
单击按钮不会加载更新页面。我不知道为什么。
【问题讨论】:
-
您是否尝试过将 res.render('update') 替换为 console.log 以查看 app.get 是否触发?
-
是的,我在路由中添加了日志,它们都在触发。似乎 res.render() 似乎没有做任何事情。
-
我从未使用过车把,所以我的快速学习热潮对我没有任何帮助。我猜问题就在那里,因为其他一切看起来都是正确的(就我的知识而言)。
-
这个人似乎有几乎相同的设置和问题,但他们的问题不是我的:stackoverflow.com/questions/37670488/…
-
您确定 update.handlebars 在正确的文件夹中吗?
标签: javascript node.js express handlebars.js