i am new on node,and i just try the basic request&response function,the server side code is:
var http = require('http');
var querystring = require('querystring');
var server = http.createServer().listen(8124);
server.on('request', function(request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function(data) {
body += data;
});
request.on('end', function() {
var post = querystring.parse(body);
console.log(post);
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end('Hello World!!!\n');
});
}
});
console.log('Server listening on 8214 ');
And the client side code is:
var http = require('http');
var querystring = require('querystring');
var postData = querystring.stringify({
'msg': 'Hello World!'
});
var options = {
hostname: 'localhost',
port: 8124,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var request = http.request(options, function(response) {
console.log('STATUS:' + response.statusCode);
console.log('HEADERS' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.on('data', function(chuck) {
console.log('BODY:' + chuck);
});
response.on('end', function() {
console.log('No more data in response!');
})
});
request.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
request.write(postData);
//request.end();
I comment out request.end(),but request.on('end', function() {...}); still works,I don't know why,please tell me what happened,thank you very much!!
via James Wei
No comments:
Post a Comment