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. 怎么在網(wǎng)頁中設(shè)置圖片進(jìn)行左右滑動2. node.js - mysql如何通過knex查詢今天和七天內(nèi)的匯總數(shù)據(jù)3. mysql 插入數(shù)值到特定的列一直失敗4. mysql 怎么做到update只更新一行數(shù)據(jù)?5. python - 在使用Pycharm時(shí)經(jīng)常看到如下的樣式,小括號里紅色的部分是什么意思呢?6. javascript - 新浪微博網(wǎng)頁版的字?jǐn)?shù)限制是怎么做的7. python2.7 - python 函數(shù)或者類 代碼的執(zhí)行順序8. 360瀏覽器與IE瀏覽器有何區(qū)別???9. javascript - 用jsonp抓取qq音樂總是說回調(diào)函數(shù)沒有定義10. sublime可以用其他編譯器替換嗎?
