【问题标题】:Seeing form data with Node.js script使用 Node.js 脚本查看表单数据
【发布时间】: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


    【解决方案1】:

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

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

    要坚持建议,请安装 NodeJSExpress

    这是guide

    【讨论】:

    • 我不太了解所有内容。我安装了 Node.js(不知道为什么我还需要 Express),我在所需的文件夹中创建了一个 server.js 文件,我在 Node.js 中运行了该文件,现在我可以在浏览器中打开localhost:8080。我还可以使用 localhost:8080/html_file_name.html 打开 html 文件(带有表单),该文件与 server.js 文件位于同一文件夹中。好像我不能在Node上一次运行两个js文件,所以我不能运行form文件。我究竟要在这里做什么才能得到想要的结果?
    猜你喜欢
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多