提问者:小点点

使用node.js脚本查看表单数据


我是web开发的初学者,所以可能我把一些事情搞混了。 我卡在了这个“阶段”。

基本上,我正在学习HTML,特别是表单。 我想测试表单是否正确发送数据。

在一本学习HTML的书中,有使用node.js(Javasript)脚本检查这一点的说明。 所以基本上,我应该用下面的代码创建一个js文件:

var http = require('http');
var querystring = require('querystring');
http.createServer(function (req, res) {
 switch(req.url) {
 case '/form':
 if (req.method == 'POST') {
 console.log("[200] " + req.method + " to " + req.url);
 var fullBody = '';
 req.on('data', function(chunk) {
 fullBody += chunk.toString();
 });
 req.on('end', function() {
 res.writeHead(200, "OK", {'Content-Type': 'text/html'});
 res.write('<html><head><title>Post data</title></head><body>');
 res.write('<style>th, td {text-align:left; padding:5px; color:black}\n');
 res.write('th {background-color:grey; color:white; min-width:10em}\n');
 res.write('td {background-color:lightgrey}\n');
 res.write('caption {font-weight:bold}</style>');
 res.write('<table border="1"><caption>Form Data</caption>');
 res.write('<tr><th>Name</th><th>Value</th>');
 var dBody = querystring.parse(fullBody);
 for (var prop in dBody) {
 res.write("<tr><td>" + prop + "</td><td>" + dBody[prop] + "</td></tr>");
 }
 res.write('</table></body></html>');
 res.end();
 });
 } else {
 console.log("[405] " + req.method + " to " + req.url);
 res.writeHead(405, "Method not supported", {'Content-Type': 'text/html'});
 res.end('<html><head><title>405 - Method not supported</title></head><body>' +
 '<h1>Method not supported.</h1></body></html>');
 }
 break;
 default:
 res.writeHead(404, "Not found", {'Content-Type': 'text/html'});
 res.end('<html><head><title>404 - Not found</title></head><body>' +
 '<h1>Not found.</h1></body></html>');
 console.log("[404] " + req.method + " to " + req.url);
 };
}).listen(8080); 

然后,我应该用node.js运行该文件,当我在表单中输入一些数据并在本地HTML文件上创建的页面中按下“Submit”按钮时,我应该被重定向到一个页面,其中有一个表显示输入的数据。 我被重定向到的url应该以“:8080/form”结尾。

我想我应该设置一个本地网络服务器模拟? 我无法一个人建立起所有的东西(太多的东西我无法一次学习),因为这本书的作者并没有把所有的东西都解释得很详细。

我在这里到底该做什么? 将form元素中action属性中的值具体更改为什么? 我是否也应该在HTML文件的基本元素中设置一个特定的href值? 我知道js文件应该和html文件在同一个文件夹中。

提前谢谢你。


共1个答案

匿名用户

您需要的是一个web服务器来为表单提供服务并接受来自该表单的POST。

NodeJS(JavaScript运行时)和Express(Web服务器)是一种选择。 还有PHP+Apache或PHP+Nginx等。

要坚持这个建议,请安装NodeJS和Express。

这里有导游。