json.js
1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var common = require('../test/common'),
http = require('http'),
util = require('util'),
formidable = common.formidable,
Buffer = require('buffer').Buffer,
port = common.port,
server;
server = http.createServer(function(req, res) {
if (req.method !== 'POST') {
res.writeHead(200, {'content-type': 'text/plain'})
res.end('Please POST a JSON payload to http://localhost:'+port+'/')
return;
}
var form = new formidable.IncomingForm(),
fields = {};
form
.on('error', function(err) {
res.writeHead(500, {'content-type': 'text/plain'});
res.end('error:\n\n'+util.inspect(err));
console.error(err);
})
.on('field', function(field, value) {
console.log(field, value);
fields[field] = value;
})
.on('end', function() {
console.log('-> post done');
res.writeHead(200, {'content-type': 'text/plain'});
res.end('received fields:\n\n '+util.inspect(fields));
});
form.parse(req);
});
server.listen(port);
console.log('listening on http://localhost:'+port+'/');
var request = http.request({
host: 'localhost',
path: '/',
port: port,
method: 'POST',
headers: { 'content-type':'application/json', 'content-length':48 }
}, function(response) {
var data = '';
console.log('\nServer responded with:');
console.log('Status:', response.statusCode);
response.pipe(process.stdout);
response.on('end', function() {
console.log('\n')
process.exit();
});
// response.on('data', function(chunk) {
// data += chunk.toString('utf8');
// });
// response.on('end', function() {
// console.log('Response Data:')
// console.log(data);
// process.exit();
// });
})
request.write('{"numbers":[1,2,3,4,5],"nested":{"key":"value"}}');
request.end();