问题陈述:我有一个简单的 HTML 表单,要求用户输入三个数字。当他们点击提交时,我会将表单传递给 node.js 文件并将每个值分配给一个变量。
下面是我的 HTML 文件:
<body>
<form action="/" method="post">
<fieldset>
First number: <input type="number" name="param1"><br>
Second number: <input type="number" name="param2"><br>
Third number: <input type="number" name="param3"><br>
<input type="submit" value="submit" />
</fieldset>
</form>
</body>
这是我对 node.js 文件的一点看法:
var http = require('http');
var math = require('mathjs');
var m = 3;
var n = 5;
var o = 7;
var p = 2;
http.createServer(function(req,res) {
function pleaseSolve () {
var comp = math.chain(m)
.add(m)
.divide(p)
.multiply(o)
.done();
res.writeHead(200, {'Content-Type': 'text/html'});
res.end("The answer is " + comp);
}
pleaseSolve();
}).listen(8080);
相反,我想要一种方法或类似的方法,使用来自 HTML 表单的输入来分配这些变量,而不是简单地对它们进行硬编码。
编辑:我已经被否决了,我已经在网上搜索了两天来寻找答案,但我还没有找到。请具有建设性,并至少链接另一篇帖子与否决票和非建设性。
最佳答案
以下 Node.js 代码将解决您的问题。 您需要一个返回主 html 文件的路由和一个获取发布数据并返回基于此数据的结果的路由。
var express = require('express')
var http = require('http');
var math = require('mathjs');
var bodyParser = require('body-parser');
var app = express()
// use body parser to easy fetch post body
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
// route to '/' to return the html file
app.get('/', function (req, res, next) {
res.sendfile('index.html');
});
//route that receives the post body and returns your computation
app.post('/solve', function (req, res, next) {
pleaseSolve(req.body, res);
});
app.listen(8080);
function pleaseSolve(parms, res) {
//get the parameters based on input name attribute from the html
//and parse strings to numbers
var m = +parms.param1;
var o = +parms.param2;
var p = +parms.param3;
var comp = math.chain(m)
.add(m)
.divide(p)
.multiply(o)
.done();
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end("The answer is " + comp);
}
关于javascript - 采用 HTML 形式并将值传递给 node.js 函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45601261/