res.render()在一种情况下工作,但不在另一种情况下工作

在下面的代码中,为什么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> 

点击button不会加载更新页面。 我不知道为什么。

我认为你的问题是你的sendRequest()函数。 您正在向/update页发送一个GET http请求,所以它正在呈现,但不在您的浏览器中。

XmlHttpRequest用于在不离开页面的情况下发送HTTP请求。 它不会告诉您的浏览器导航到该地址。

我想你想要的是告诉你的浏览器导航到/update页面。

例如

 function sendRequest() { window.location = "/update"; }; 

试试看,它应该做你想做的。