1let request = require('request')
2
3const formData = {
4 // Pass a simple key-value pair
5 my_field: 'my_value',
6 // Pass data via Buffers
7 my_buffer: Buffer.from([1, 2, 3]),
8 // Pass data via Streams
9 my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
10 // Pass multiple values /w an Array
11 attachments: [
12 fs.createReadStream(__dirname + '/attachment1.jpg'),
13 fs.createReadStream(__dirname + '/attachment2.jpg')
14 ],
15 // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
16 // Use case: for some types of streams, you'll need to provide "file"-related information manually.
17 // See the `form-data` README for more information about options: https://github.com/form-data/form-data
18 custom_file: {
19 value: fs.createReadStream('/dev/urandom'),
20 options: {
21 filename: 'topsecret.jpg',
22 contentType: 'image/jpeg'
23 }
24 }
25};
26request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
27 if (err) {
28 return console.error('upload failed:', err);
29 }
30 console.log('Upload successful! Server responded with:', body);
31});
1const https = require('https');
2
3https.get('https://jsonplaceholder.typicode.com/users', res => {
4 let data = [];
5 const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date';
6 console.log('Status Code:', res.statusCode);
7 console.log('Date in Response header:', headerDate);
8
9 res.on('data', chunk => {
10 data.push(chunk);
11 });
12
13 res.on('end', () => {
14 console.log('Response ended: ');
15 const users = JSON.parse(Buffer.concat(data).toString());
16
17 for(user of users) {
18 console.log(`Got user with id: ${user.id}, name: ${user.name}`);
19 }
20 });
21}).on('error', err => {
22 console.log('Error: ', err.message);
23});
1const request = require('request');
2request('http://www.google.com', function (error, response, body) {
3 console.error('error:', error); // Print the error if one occurred
4 console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
5 console.log('body:', body); // Print the HTML for the Google homepage.
6});