Why can’t page data captured through post be displayed on the page

  node.js, question

Js code

var http = require("http"),
 fs = require("fs"),
 querystring = require("querystring"),
 url = require("url");
 
 http.createServer(function(req,res){
 var postdata="";
 var query="what";
 var pathname = url.parse(req.url).pathname;
 
 req.setEncoding("utf8");
 if(pathname=="/"){
 Var indexPage = fs.readFileSync ("form.html");
 res.writeHead(200,{"Content-Type":"text/html"});
 res.end(indexPage);
 bracket
 if(pathname=="/about"){
 req.on("data",function(chunk){
 Postdataplus = chunk;
 });
 req.on("end",function() {
 console.log(postdata);
 query = querystring.parse(postdata);
 console.log(query);
 });
 res.writeHead(200, {"Content-Type":"text/plain"});
 console.log(query.Name);
 console.log(query.number);
 Res.write(query.number plus "and" plus query.number);
 res.end();
 bracket
 else{
 res.writeHead(404,{"Content-Type":"text/plain"});
 res.end("Can not find the source");
 bracket
 }).listen(2000,"127.0.0.1");
 
 console.log("The server is running at port 2000");
 
 This is html code
 
 <!  DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 < title > form filling < /title >
 </head>
 <body>
 <form action="/about" method="post">
 <p> Name: <input type="text" name="Name"></p>
 <p>SchoolNumber:<input type="text" name="number"></p>
 < p><input type="submit" value= "submit" > < /p >
 </form>
 </body>
 </html>
 
 Execution result diagram:

clipboard.png

clipboard.png

I am very grateful to ask the great god to solve the problem.

Cause analysis: the callback function execution order problem, add some print information to see图片描述

The line res.write () returns that the query you initially defined did not perform the operations in req.on (). At this time, the query is still the string “what” you defined. It is not a json object, so there is no number attribute, so it is undefined.
Solution: you can write res.write () in req.on (), like this:图片描述