res.render()在一种情况下工作,但不在另一种情况下工作
问题描述:
在下面的代码中,为什么res.render('home');
工作,但是res.render('update');
不工作?res.render()在一种情况下工作,但不在另一种情况下工作
这是使用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>
单击该按钮不会加载更新页面。我不知道为什么。
答
我认为你的问题是你的sendRequest()
函数。您正在向/update
页面发送GET http请求,因此它正在呈现,但不在您的浏览器中。
XmlHttpRequest
用于在不离开页面的情况下发送HTTP请求。它不会告诉您的浏览器导航到该地址。
我想你想要的是告诉你的浏览器导航到/update
页面。
例如
function sendRequest() {
window.location = "/update";
};
尝试这一点,它应该做你想要什么。
+1
这解决了它!一位绅士和一位学者!谢谢! –
您是否尝试用console.log替换res.render('update')以查看app.get是否会触发? –
是的,我在路线上写了一个日志,他们俩都在射击。看起来res.render()似乎没有做任何事情。 –
我从来没有使用过把手,所以我的快速学习狂潮并没有帮助我。我猜这个问题在那里,因为所有其他东西都是对的(因为我的知识值得)。 –