html - node.js為啥抓取不了前端傳過來的數據?
問題描述
用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); }elseconsole.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>
求大神指教
問題解答
回答1:你只處理了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); } elseconsole.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>
相關文章:
1. 數組按鍵值封裝!2. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題3. docker不顯示端口映射呢?4. python - flask _sqlalchemy 能否用中文作為索引條件5. java - 阿里的開發手冊中為什么禁用map來作為查詢的接受類?6. python3.x - git bash如何運行.bat文件?7. javascript - ES6規范下 repeat 函數報錯 Invalid count value8. html5 - 使用echarts中的圖表 一個頁面導入了好幾個js圖表 實現echarts圖表隨著瀏覽器窗口變化而變化時出現了問題9. javascript - webpack中alias配置中的“@”是什么意思?10. javascript - 為什么創建多行多列的表格最后只有一行內有表格
