2017-06-26 53 views
0

我想將我的表單數據顯示到另一個html頁面。這是我的server.js顯示從node.js服務器到html頁面的數據

var express = require('express'); 
 
var bodyParser = require('body-parser'); 
 
var app  = express(); 
 
var path=require('path'); 
 

 
app.use(bodyParser.urlencoded({ extended: true })); 
 

 

 
app.use(express.static(path.join(__dirname, '/'))); 
 
app.post('/myaction.html', function(req, res) { 
 
    res.send('You sent the name "' + req.body.name + '".'); 
 
}); 
 

 
app.listen(8080, function() { 
 
    console.log('Server running at http://127.0.0.1:8080/'); 
 
});
這是我的 '的index.html'

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<meta charset="utf-8" /> 
 
<title>Demo Form</title> 
 
</head> 
 
<body> 
 
<div id="contact"> 
 
    <h1>Enter the values</h1> 
 
    <form action="/myaction.html" method="post"> 
 
     <fieldset> 
 
      <label for="name">Name:</label> 
 
      <input type="text" id="name" name="name" placeholder="Enter your full name" /> 
 

 
      <label for="email">Email:</label> 
 
      <input type="email" id="email" placeholder="Enter your email address" /> 
 

 
      <label for="message">Message:</label> 
 
      <textarea id="message" placeholder="What's on your mind?"></textarea> 
 
      
 
      <input type="submit" value="Send message" /> 
 

 
     </fieldset> 
 
    </form> 
 
</div> 
 
</body> 
 
</html>

現在,它工作正常,並且名稱中反映myaction.html頁面。但我想稍微設定'myaction.html'頁面的樣式,並使其看起來更具可視性。有沒有辦法在頁面中添加更多的html標籤和文本,或者在已經存在的頁面中顯示錶單數據?

+0

https://expressjs.com/en/guide/using-template-engines.html – Quentin

回答

0

使用模板引擎。 EJS是一個很好的例子。首先,您必須在server.js中使用npm install ejs,然後使用app.set('view engine', 'ejs');。之後,您將能夠在名爲views的項目中創建一個新文件夾,並且您可以在其中創建index.ejs和其他視圖文件。在你的server.js裏面你可以使用res.render('index.ejs', {data: aJavascriptVariable, data1: moreVars});。最後,要在.ejs文件中使用這些變量,您可以使用<%= data%>或<%= data1%>。當然,html可以寫在一個.ejs文件中。

相關問題