html - node.js為啥抓取不了前端傳過來的數(shù)據(jù)?
問題描述
用node.js抓取不了前端表單的數(shù)據(jù),哭哭哭這是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部分的數(shù)據(jù),然而前端的提交方法是get...建議去了解一下get和post的基本區(qū)別...
修改之后的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 () { //去掉參數(shù) 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>
相關(guān)文章:
1. android-studio - Android Studio 運行項目的時候一堆警告,跑步起來!?2. dockerfile - [docker build image失敗- npm install]3. mysql - 新浪微博中的關(guān)注功能是如何設(shè)計表結(jié)構(gòu)的?4. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問題。5. 如何解決Centos下Docker服務(wù)啟動無響應(yīng),且輸入docker命令無響應(yīng)?6. angular.js - 關(guān)于$apply()7. MySQL數(shù)據(jù)庫中文亂碼的原因8. 表單提交驗證,沒反應(yīng),求老師指點9. nignx - docker內(nèi)nginx 80端口被占用10. angular.js - Ionic 集成crosswalk后生成的apk在android4.4.2上安裝失敗???
