[英]Take HTML form and pass values to variables in node.js function
Problem Statement: I have a simple HTML form that asks for three numbers from the user. 问题陈述:我有一个简单的HTML表单,要求用户提供三个数字。 When they hit submit, I would the form to be passed to a node.js file and assign each value to a variable.
当他们点击提交时,我会将表单传递到node.js文件,并将每个值分配给一个变量。
Below is my HTML file: 以下是我的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>
And here is the little bit I have for the node.js file: 这是我对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);
Instead, I would like a method or something similar that would assign those variables using input from the HTML form rather than me simply hard-coding them. 相反,我想要一种方法或类似的方法,可以使用HTML表单的输入来分配这些变量,而不是简单地对其进行硬编码。
EDIT: I've already been downvoted and I have been searching the web for two days for an answer for this and I haven't found one. 编辑:我已经被否决了,我已经在网上搜索了两天以寻求答案,但是我还没有找到答案。 Please be constructive and at least link another post versus downvoting and being non-constructive.
请保持建设性,并至少将另一个帖子与否决和非建设性联系起来。
This following Node.js code will solve your question. 以下以下Node.js代码将解决您的问题。 You need a route to return your main html file and a route that gets post data and returns a result based on this data.
您需要一条路由来返回您的主要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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.