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