使用http获取html表单数据

我需要从简单的HTML表单(代码如下)获取数据,并将其发送到API( http://netology.tomilomark.ru/doc/#api-ND ),使哈希出来。 这里是html表单代码:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Form</title> </head> <body> <form action="/sendForm"> Name:<br> <input type="text" name="firstName" value=""> <br> Surname:<br> <input type="text" name="lastName" value=""> <br><br> <input type="submit" value="Send"> </form> </body> 

这就是我在服务器端所得到的:

 "use strict"; const http = require("http"); const fs = require("fs"); const PORT = 3000; let resObject = {}; let hash; // Code that sends name + surname to the API and creates hash // ------------- begin ------------- let options = { hostname: "netology.tomilomark.ru", path: "/api/v1/hash", method: "POST", headers: { "firstName": "Evgeny", "Content-Type": "application/json" } }; let req = http.request(options, (res) => { let resString = ""; res.on("data", (data) => { resString += data; }); res.on("end", () => { console.log(resString); hash = resString["hash"]; }) }); let reqMessage = JSON.stringify({"lastName": "Kobzev"}); req.write(reqMessage); req.end(); resObject.firstName = "Evgeny"; resObject.lastName = "Kobzev"; console.log(JSON.stringify(resObject)); // -------------- end -------------- // Create web server that loads the html file // ------------- begin ------------- const server = http.createServer((req, res) => { fs.readFile("./logs/form.html", (err, file) => { res.writeHead(200, {'Content-Type': 'text/html','Content-Length':file.length}); res.write(file); }); }); server.on("error", (err) => console.error(err)); server.on("listening", () => console.log(`Start HTTP on port ${PORT}`)); server.listen(PORT); // -------------- end -------------- 

我怎样才能从这种简单的forms获取数据,然后将其发送到API? 问题是我需要使用一个低层次的抽象解决scheme:http和querystring。

任何帮助将不胜感激!

Solutions Collecting From Web of "使用http获取html表单数据"

工作了几分钟后,我得到了代码。在我的代码中,我正在打印哈希值在terminal。这里是我的代码

 var qs = require('querystring'); var request=require('request'); var util=require('util'); const http= require("http"); const fs= require("fs"); var hash=require('object-hash'); const server = http.createServer((req, res) => { if (req.url === '/sendForm' && req.method === 'POST') { var body = ""; req.on('data', function (chunk) { body += chunk; }); req.on('end', function () { var post= qs.parse(body); var Fs=hash({NAME:post.firstName}); var Sn=hash({SURNAME:post.surName}); console.log("FirstName:"+post.firstName); console.log("SurName:"+post.surName) console.log("Hashed Value Of FirstName:"+Fs); console.log("Hashed Value Of SurName:"+Sn); res.end("successfully submitted"); }); } fs.readFile("./sample.html", (err, file) => { res.writeHead(200, {'content-type': 'text/html','Content-Length':file.length}); res.end(file); }); }).listen(3000,function(){ console.log("Server Listening on 3000"); }); 

希望这对你有帮助…