2017-03-17 239 views
2

在下面的代碼中,爲什麼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> 

單擊該按鈕不會加載更新頁面。我不知道爲什麼。

+1

您是否嘗試用console.log替換res.render('update')以查看app.get是否會觸發? –

+0

是的,我在路線上寫了一個日誌,他們倆都在射擊。看起來res.render()似乎沒有做任何事情。 –

+1

我從來沒有使用過把手,所以我的快速學習狂潮並沒有幫助我。我猜這個問題在那裏,因爲所有其他東西都是對的(因爲我的知識值得)。 –

回答

2

我認爲你的問題是你的sendRequest()函數。您正在向/update頁面發送GET http請求,因此它正在呈現,但不在您的瀏覽器中。

XmlHttpRequest用於在不離開頁面的情況下發送HTTP請求。它不會告訴您的瀏覽器導航到該地址。

我想你想要的是告訴你的瀏覽器導航到/update頁面。

例如

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

嘗試這一點,它應該做你想要什麼。

+1

這解決了它!一位紳士和一位學者!謝謝! –

相關問題