【发布时间】:2020-11-17 22:10:16
【问题描述】:
我是 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 文件上创建的页面中按“提交”按钮时,我应该被重定向到一个页面带有显示输入数据的表格。我被重定向到的 url 应该以“:8080/form”结尾。
我想我应该设置一个本地网络服务器模拟?我无法自己设置所有内容(我一次无法学习的东西太多),因为本书的作者没有详细解释所有内容。
我究竟应该在这里做什么?将表单元素中 action 属性中的值更改为究竟是什么?我是否还应该在 HTML 文件的基本元素中设置特定的任何特定 href 值?我知道js文件应该和html文件在同一个文件夹中。
提前致谢。
【问题讨论】:
标签: javascript html node.js forms