Javascript 不使用express从表单转换正文数据
目标: 目标是从输入姓名和乐队的表单中呈现数据。提交后,您将被重定向到一个新页面,该页面将显示Javascript 不使用express从表单转换正文数据,javascript,node.js,express,Javascript,Node.js,Express,目标: 目标是从输入姓名和乐队的表单中呈现数据。提交后,您将被重定向到一个新页面,该页面将显示 Name: John Doe Favorite Band: The Who 问题: 我无法在本练习中使用express模块,我使用它来呈现数据,但在页面上显示如下: Your name is: name=John+Doe&band=The+Who Your favorite band is: name=John+Doe&band=The+Who 我确实意识到我在寻找body.nam
Name: John Doe
Favorite Band: The Who
问题:
我无法在本练习中使用express模块,我使用它来呈现数据,但在页面上显示如下:
Your name is: name=John+Doe&band=The+Who
Your favorite band is: name=John+Doe&band=The+Who
我确实意识到我在寻找body.name和body.band之类的东西,但我一直收到错误消息
我尝试过的:
我尝试过主体解析器和查询字符串,但我在研究中发现的大多数示例都涉及到能够使用express,我正在努力进行翻译
我的要求:
我只是需要一些关于如何解决这个问题的指导
这是我的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>
欢迎来到我的邮寄表格!
请使用此表格邮寄:
提交
这是我的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}));
让http=require('http');
设fs=require('fs');
让server=http.createServer(handleRequest);
const port=process.env.port | 3000;
函数handleRequest(请求、恢复){
var path=req.url;
如果(请求方法==“获取”){
res.writeHead(200,{“内容类型”:“text/html”});
创建读取流(“postalServiceHTML.html”,“UTF-8”).pipe(res);
}else if(req.method==“POST”&&path==“谢谢”){
var body=“”;
请求打开(“数据”,功能(块){
body+=块;
});
}
请求开启(“结束”,函数(){
res.writeHead(200,{“内容类型”:“text/html”})
res.end(`
表格结果
你的表格结果
您的名字是:${body}
你最喜欢的乐队是:${body}
`);
});
}
listen(端口,()=>console.log(服务器在端口${port}上运行));
首先,您必须使用正文解析器来解析请求正文
并且在您的渲染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>
`);
});
}
res.end(`
表格结果
你的表格结果
您的名字是:${body.name}//这里有个变化
你最喜欢的乐队是:${body.band}//这里有个变化
`);
});
}
如果您不想使用body解析器,并且您只想让这个示例起作用,那么您可以从body字符串中获取名称和喜爱的乐队。。。您必须了解如何让我演示工作版本:
postalServiceHTML.html-未更改
服务器-小更改:
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}`));
下面是我的一位合作伙伴在不使用qs或体解析器的情况下帮助我解决这个问题的一种方法
// 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);
});
或者先除以&再除以=,这很难写成“一行”(除了iLife;-),但更可靠。同样有趣的是,投票。