[英]node.js: How can I output a variable directly to index.html
如何從index.html獲取用戶輸入,在node中處理並將結果輸出回index.html? 而不是像當前那樣輸出到新頁面。
表格文件
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile('index.html', { root: __dirname});
app.post('/mess', function(req, res){ //means same dir
var userNum1 = req.body.num1;
var userNum2 = req.body.num1;
var answer = parseInt (userNum1) + parseInt (userNum2);
res.send ('The answer is ' + answer);
});
app.listen(80);
index.html
<!DOCTYPE html>
<html>
<head>
<title>Forms></title>
</head>
<body>
<form action="mess" method="post">
<p>Enter a number:</p>
<input type="text" name="num1" placeholder="..." />
<br>
<p>Enter a number:</p>
<input type="text" name="num2" placeholder="..." />
<br>
<button type="submit">Submit</button>
<br>
</form>
</body>
</html>
可能最簡單的方法是使用ejs
。
首先npm install ejs
。 然后將其添加到您的Express應用代碼中:
app.set('view engine', 'ejs');
// this allows you to render .html files as templates in addition to .ejs
app.engine('html', require('ejs').renderFile);
在路由處理程序中,您只需執行以下操作:
res.render('form', { answer: 'foo' });
然后您的模板(例如./views/form.html
)將如下所示:
<html>
<p> The answer is <%= answer %> </p>
</html>
EJS的替代方法是使用socket.io。 您可以將事件處理程序附加到每個條目或提交按鈕,然后使用socket.io將其從客戶端發送到服務器,進行處理並將其發送回去。 然后,頁面可以在從服務器接收數據時進行更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.