You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.8 KiB

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