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. html5 - 百度Ueditor代码高亮和代码段滚动条冲突是怎么回事?2. javascript - 静态页面引公共头尾文件,js怎么写吖?3. docker gitlab 如何git clone?4. javascript - 读取页面源码,页面中所有的换行都被当成<br/>读取出来 了,,求解应该怎么让它被正确的解析5. javascript - 关于一段 for 循环代码执行顺序的问题6. java - 3个dao的数据根据请求参数选择一个映射到一个url上,怎么写比较好?7. docker 17.03 怎么配置 registry mirror ?8. docker网络端口映射,没有方便点的操作方法么?9. 如何调整IDEA中直接运行java程序的日志输出级别?10. docker绑定了nginx端口 外部访问不到