rdsedmundo

vanilla http nodejs

Mar 28th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const http = require('http');
  2.  
  3. const API = '';
  4.  
  5. class Lambda {
  6.   constructor() {
  7.     this.get(
  8.       `${API}/categories`,
  9.       (data) => {
  10.         console.log('First category is', data.categories[0]);
  11.       });
  12.   }
  13.  
  14.   get(url, callback, error) {
  15.     const request = http.get(
  16.       url,
  17.       (response) => {
  18.         response.setEncoding('utf8');
  19.  
  20.         let body = '';
  21.  
  22.         response.on('data', (chunk) => {
  23.           body += chunk;
  24.         });
  25.  
  26.         response.on('end', () => {
  27.           body = JSON.parse(body);
  28.           callback(body);
  29.         });
  30.  
  31.       }
  32.     );
  33.    
  34.     request.on('error', error);
  35.   }
  36.  
  37.   post(url, data, callback, error) {
  38.     const options = {
  39.       hostname: 'www.someapi.com',
  40.       port: 80,
  41.       path: '/seturl',
  42.       method: 'POST',
  43.       headers: {
  44.         'Content-Type': 'application/json',
  45.         'Content-Length': Buffer.byteLength(JSON.stringify(data)),
  46.       }
  47.     };
  48.  
  49.     const request = http.request(
  50.       options,
  51.       (response) => {
  52.         response.setEncoding('utf8');
  53.  
  54.         let body = '';
  55.  
  56.         response.on('data', (chunk) => {
  57.           body += chunk;
  58.         });
  59.  
  60.         response.on('end', () => {
  61.           body = JSON.parse(body);
  62.           callback(body);
  63.         });
  64.       }
  65.     );
  66.  
  67.     request.write(data);
  68.     request.end();
  69.   }
  70. }
  71.  
  72. module.exports = new Lambda();
Add Comment
Please, Sign In to add comment