問題描述
使用 Node.js 腳本查看表單數據 (Seeing form data with Node.js script)
我是 Web 開發的初學者,所以我可能混淆了一些東西。我被困在這個“階段”。
基本上,我正在學習 HTML,尤其是 Forms。我想測試表單是否正確發送數據。
在學習 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 文件在同一個文件夾中。
提前致謝。
我到底應該在這裡做什麼?將表單元素中 action 屬性中的值更改為究竟是什麼?我是否還應該在 HTML 文件的基本元素中設置特定的任何特定 href 值?我知道 js 文件應該與 html 文件在同一個文件夾中。提前致謝。
我到底應該在這裡做什麼?將表單元素中 action 屬性中的值更改為究竟是什麼?我是否還應該在 HTML 文件的基本元素中設置特定的任何特定 href 值?我知道 js 文件應該與 html 文件在同一個文件夾中。提前致謝。
參考解法
方法 1:
What you need is a web server to serve the form and accept a POST from that form.
NodeJS (a JavaScript runtime) and Express (Web Server) is one option. There's also PHP + Apache, or PHP + Nginx, etc.
To stick with the recommendation, install NodeJS and Express.
Here is a guide.
(by mandroid000、Russell)