1.我不知道我代码哪里写错了,只要不注释掉res.writeHead()就会有错。 2.弱弱地问一句,我怎么把一个对象的某个属性返回去呀? 比如我写一个res.wirite(data.a)就说要转成字符串,但是用querystring.stringify却没有结果,然后试了一下JS里的toString(),却说没定义。 //服务器 var http = require(‘http’); var url = require(‘url’); var util = require(‘util’); var qs = require(‘querystring’); http.createServer(function(req,res){ var data = '’; req.on('data’,function(chunk){ data+=chunk; });
req.on('end',function(){
data = qs.parse(data);
});
res.writeHead(200, {
'Content-Length': data.length,
'Content-Type': 'text/plain' });
res.write('hello');
//res.write(data.a);
res.end("hello");
}).listen(3000); console.log(“!!!”);
//模拟一个POST请求 var http=require(‘http’); var qs=require(‘querystring’);
var post_data={a:123,time:new Date().getTime()}; var content=qs.stringify(post_data);
var options = { host: 'localhost’, port: 3000, path: '/’, method: 'POST’, headers:{ 'Content-Type’:’application/x-www-form-urlencoded’, 'Content-Length’:content.length } }; console.log("post options:\n",options); console.log("content:",content); console.log(“\n”);
var req = http.request(options, function(res) { console.log("statusCode: ", res.statusCode); console.log("headers: ", res.headers); var _data=’’; res.on('data’, function(chunk){ _data += chunk; }); res.on('end’, function(){ console.log("\n—>>\nresult:",_data) }); });
req.write(content); req.end();
问题所在:
req.on('end',function(){
data = qs.parse(data);
});
res.writeHead(200, {
'Content-Length': data.length,
提示: 异步
var http=require(‘http’); var qs=require(‘querystring’); var post_data={a:123,time:new Date().getTime()};//这是需要提交的数据 var content=qs.stringify(post_data);
var options = { host: 'localhost’, port: 3000, path: '/’, method: 'POST’, headers:{ 'Content-Type’:’application/x-www-form-urlencoded’, 'Content-Length’:content.length } }; console.log("post options:\n",options); console.log("content:",content); console.log(“\n”);
var req = http.request(options, function(res) { console.log("statusCode: ", res.statusCode); console.log("headers: ", res.headers); var _data=’’; res.on('data’, function(chunk){ _data += chunk; console.log(_data); }); res.on('end’, function(){ //data = qs.parse(_data); console.log(‘end is emitted’); console.log("\n—>>\nresult:",_data) }); });
req.write(content); req.end();
//服务器 var http = require(‘http’); var url = require(‘url’); var util = require(‘util’); var qs = require(‘querystring’); http.createServer(function(req,res){ var data = '’; req.on('data’,function(chunk){ data+=chunk; });
req.on('end’,function(){ res.writeHead(200, { 'Content-Length’: data.length, 'Content-Type’: ‘text/plain’ }); data = qs.parse(data); console.log(data.a.toString()); res.write(data.a.toString()); res.end(‘hello’); //data = qs.parse(data); console.log(data); }); }).listen(3000); console.log(“!!!”);
在客户端 我的res.on(end)事件始终没有反应……这是为什么?