简体   繁体   English

从表单转换主体数据而不进行快速表达

[英]Converting body data from form without express

Goal: 目标:

The goal is to render data from the form where you enter your name and band. 目的是从您输入姓名和乐队的表单中呈现数据。 Once you submit you will be redirected to a new page which will state 提交后,您将被重定向到一个新页面,该页面将显示

Name: John Doe
Favorite Band: The Who

Problem: 问题:

I cannot use the express module for this exercise and I got it to render the data but it comes out like this on the page: 我不能在此练习中使用express模块​​,但我得到了它来呈现数据,但它在页面上如下所示:

Your name is: name=John+Doe&band=The+Who
Your favorite band is: name=John+Doe&band=The+Who

I do realize that I am looking for something like body.name and body.band but I keep getting error messages. 我确实意识到我在寻找诸如body.name和body.band之类的东西,但是我一直收到错误消息。

What I have tried: 我尝试过的

I have tried body-parser and query string but most of the examples I have found in researching have all dealt with being able to use express I am struggling with the translation. 我已经尝试了body-parser和查询字符串,但是我在研究中发现的大多数示例都处理了能够使用Express的问题,而我正在努力进行翻译。

What I am asking for: 我要的是:

I just need some guidance on how to solve this. 我只需要一些有关如何解决此问题的指导。

Here is my html file: 这是我的html文件:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to my post form!</title>
</head>
<body>
 <div class='container'>
   <div class='jumbotron text-center'>
     <h1>Please post using this form:</h1>
   </div>
   <div class="row">
     <div class="col-sm-12 text-center">
       <form action="http://localhost:3000/thanks" method="POST">
        <input name="name" placeholder="enter your name">
        <input name="band" placeholder="enter your favorite band">
        <button type='submit'>submit</button>
      </form>
    </div>
  </div>
</div>
</body>
</html>

Here is my server.js file and what I currently have that works but gives me the output I showed above: 这是我的server.js文件,目前可以正常运行,但是可以得到上面显示的输出:

let http = require('http');
let fs = require('fs');
let server = http.createServer(handleRequest);
const port = process.env.PORT || 3000;
function handleRequest(req, res) {
var path = req.url;
if (req.method === "GET"){
  res.writeHead(200, {"Content-Type": "text/html"});
  fs.createReadStream("postalServiceHTML.html", "UTF-8").pipe(res);
  } else if (req.method === "POST" && path == '/thanks'){
  var body = "";
  req.on("data", function(chunk){
  body += chunk;
  });
}
  req.on("end", function(){
  res.writeHead(200, {"Content-Type": "text/html"})
  res.end(`
  <!DOCTYPE HTML>
  <html>
  <head>
  <title> Form Results </title>
  </head>
  <body>
  <h1> Your Form Results </h1>
  <p> Your name is: ${body} </p>
  <p> Your favorite band is: ${body} </p>
  </body>
  </html>
  `);
  });
}
 server.listen(port, () => console.log(Server is running on port ${port}));

Let me present working version: 让我介绍一下工作版本:
postalServiceHTML.html - unchanged postalServiceHTML.html-不变
Server - small changes: 服务器-小改动:

var qs = require('qs');
let http = require('http');
let fs = require('fs');
let server = http.createServer(handleRequest);
const port = process.env.PORT || 3000;
function handleRequest(req, res) {
    var path = req.url;
    if (req.method == "GET") {
        res.writeHead(200, { "Content-Type": "text/html" });
        fs.createReadStream("postalServiceHTML.html", "UTF-8").pipe(res);
    } else if (req.method == "POST" && path == '/thanks') {
        var body = "";
        req.on("data", function (chunk) {
            body += chunk;
        });
    }
    req.on("end", function () {
        res.writeHead(200, { "Content-Type": "text/html" })
        if(this.method == "POST") {
            var json = qs.parse(body);
            res.end(`<!DOCTYPE HTML><html><head><title> Form Results </title></head><body>
                <h1> Your Form Results </h1><p> Your name is: ${json.name} </p>
                <p> Your favorite band is: ${json.band} </p></body></html>`);
        }
    });
}
server.listen(port, () => console.log(`Server is running on port ${port}`));

Possible to use qs ? 可以使用qs吗? It is used by body-parser too. 身体解析器也使用它。

In case you have simple values like here and do not care about attempts to send some bad input, you can make it a single purpose for example like this: 如果您具有像这里这样的简单值,并且不关心尝试发送一些错误的输入,则可以将其作为一个单一目的,例如:

 var body = "name=John+Doe&band=The+Who%26Escape+test"; var strigified = '{' + body.replace(/([^=&]+)=/g, '"$1"='). // "name"=John+Doe&"band"=The+Who replace(/=([^&=]+)[&]*/g, ':"$1",'). // "name":"John+Doe","band":"The+Who", replace(/\\+/g, ' '). // "name":"John Doe","band":"The Who", replace(/,$/g,'') + // "name":"John Doe","band":"The Who" '}'; var json = JSON.parse(unescape(strigified)); console.log(JSON.stringify(json, null, 2)); 

Here is a way a partner of mine helped me figure this out without using qs or body-parser 这是我的一个合作伙伴帮助我解决此问题的方法,而无需使用qs或body-parser

// Dependencies
const http = require("http");
const fs = require("fs");
const PORT = 7667;
const server = http.createServer(handleRequest);
function handleRequest(req, res) {
 const path = req.url;
 switch (path) {
 case "/thanks":
   return renderThankYouPage(req, res);
 default:
   return renderWelcomePage(req, res);
 }
}
function renderWelcomePage(req, res) {
 fs.readFile("./postalServiceHTML.html", function(err, data) {
   if (err) {
     res.writeHead(500, { "Content-Type": "text/html" });
     res.end("<html><head><title>Oops</title></head><body><h1>Oops, there was an error</h1></html>");
   }
   else {
     // We then respond to the client with the HTML page by specifically telling the browser that we are delivering
     // an html file.
     res.writeHead(200, { "Content-Type": "text/html" });
     res.end(data);
   }
 });
}
// Jay, you could even declare an array and use that as a temporary storage like this to keep track of all the inputs
let db = [];
function renderThankYouPage(req, res) {
 // Saving the request posted data as a variable.
   let requestData = "";
   // Variable declare to store the user inputs
   let userName;
   let bandName;
   let output;
 let myHTML =
       "<html><head><title>Hello Noder!</title></head><body><h1>Oops, I didn't get any data</h1></body></html>";
 // When the server receives data, it will add it to requestData.
 req.on("data", function(data) {
       requestData += data;
       // Parse the user inputs
       userName = data.toString().split('&')[0].split('=')[1].replace(/[+]/g, ' ');
       bandName = data.toString().split('&')[1].split('=')[1].replace(/[+]/g, ' ');
       // create a different user object for each input
       let userInput = {
           userName: userName,
           bandName: bandName
       }
       // Store into a dummy database - array
       db.push(userInput);
       console.log(userInput);
       console.log(db);
       // Generate the data to be render onto the client side
       for(let i = 0; i < db.length; i++) {
           output = <li> Name: ${db[i].userName} Band: ${db[i].bandName}</li>
           console.log(output);
       }
       console.log(output);
       // Content to be render back to client
   myHTML =
     "<html><head><title>Hello Noder!</title></head><body>" +
     "<h1>Thank you for the data: </h1> <code> " +
           output +
           "</code></body></html>";
 });
 // When the request has ended...
 req.on("end", function() {
   res.writeHead(200, { "Content-Type": "text/html" });
   res.end(myHTML);
 });
}
// Starts our server.
server.listen(PORT, function() {
 console.log("Server listening on: http://localhost:" + PORT);
});

first you have to use body-parser to parse the body of the request and in your render html 首先,您必须使用body-parser解析请求的主体,并在渲染html中

  res.end(`
  <!DOCTYPE HTML>
  <html>
  <head>
  <title> Form Results </title>
  </head>
  <body>
  <h1> Your Form Results </h1>
  <p> Your name is: ${body.name} </p> // here a change
  <p> Your favorite band is: ${body.band} </p> // here a change
  </body>
  </html>
  `);
  });
}

if you dont want to use body parser, and you want just this example to work you could grab the name and favorite band from the body string... you have to find how 如果您不想使用正文解析器,并且只想使此示例正常工作,则可以从正文字符串中获取名称和喜欢的乐队...您必须找到如何

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM