用node.js抓取不了前端表单的数据,哭哭哭
这是node.js代码
var http=require("http");
var url=require("url");
var dns=require("dns");
var fs=require("fs");
var querystring=require("querystring");
var postdata="";
http.createServer(function(req,res){
req.setEncoding("utf8");
//var readPath=dirname+"/"+url.parse('a.html').pathname;
var pathname=url.parse(req.url).pathname;
if(pathname==="/"){
res.writeHead(200,{'Content-Type':'text/html'});
var indexpage=fs.readFileSync("a.html");
//console.log(indexpage);
res.end(indexpage);
}
if(pathname==="/about"){
res.writeHead(200,{'Content-Type':'text/plain'});
req.addListener("data",function(chunk){
if(chunk){
postdata+=chunk;
console.log(chunk);
}
else
console.log("no data emit")
});
req.addListener("end",function(postdata){
var a=querystring.parse(postdata);
console.log(postdata)
console.log(a);
res.end(a.text);
});
}
console.log("Server has been running on port 3000");
}).listen("3000","127.0.0.1");
这是HTML代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="sinson">
</head>
<body>
<form action="/about" method="get">
<input type="text" name="text">
<input type="submit" value="提交">
</form>
</body>
</html>
求大神指教
高洛峰2017-04-17 15:02:14
你只處理了body
部分的數據,然而前端的提交方法是get
...
建議去了解get
和post
的基本區別...
修改後的app.js
var http = require("http");
var url = require("url");
var dns = require("dns");
var fs = require("fs");
var querystring = require("querystring");
var postdata = "";
http.createServer(function (req, res) {
req.setEncoding("utf8");
// var readPath=dirname+"/"+url.parse('a.html').pathname;
var pathname = url.parse(req.url).pathname;
if (pathname === "/") {
res.writeHead(200, { 'Content-Type': 'text/html' });
var indexpage = fs.readFileSync("a.html");
// console.log(indexpage);
res.end(indexpage);
}
if (pathname === "/about") {
res.writeHead(200, { 'Content-Type': 'text/plain' });
req.addListener("data", function (chunk) {
if (chunk) {
postdata += chunk;
console.log(chunk);
} else
console.log("no data emit");
});
req.addListener("end", function () { //去掉参数
var a = querystring.parse(postdata);
console.log(postdata);
console.log(a);
res.end(a.text);
});
}
}).listen("3000", "127.0.0.1");
console.log("Server has been running on port 3000");//提到外面比较好
a.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="sinson">
</head>
<body>
<form action="/about" method="POST"> <!--改为POST-->
<input type="text" name="text">
<input type="submit" value="提交">
</form>
</body>
</html>