【问题标题】:res.render() works in one situation but not in anotherres.render() 在一种情况下有效,但在另一种情况下无效
【发布时间】: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>

ma​​in.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


【解决方案1】:

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

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

我认为您想要告诉您的浏览器导航到/update 页面。

例如

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

试试吧,它应该会做你想做的事。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多