let request =require('request')const formData ={// Pass a simple key-value pairmy_field:'my_value',// Pass data via Buffersmy_buffer:Buffer.from([1,2,3]),// Pass data via Streamsmy_file: fs.createReadStream(__dirname +'/unicycle.jpg'),// Pass multiple values /w an Arrayattachments:[
fs.createReadStream(__dirname +'/attachment1.jpg'),
fs.createReadStream(__dirname +'/attachment2.jpg')],// Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}// Use case: for some types of streams, you'll need to provide "file"-related information manually.// See the `form-data` README for more information about options: https://github.com/form-data/form-datacustom_file:{value: fs.createReadStream('/dev/urandom'),options:{filename:'topsecret.jpg',contentType:'image/jpeg'}}};
request.post({url:'http://service.com/upload',formData: formData},functionoptionalCallback(err, httpResponse, body){if(err){returnconsole.error('upload failed:', err);}console.log('Upload successful! Server responded with:', body);});
var http =require('http');//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'var options ={host:'www.random.org',path:'/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'};callback=function(response){var str ='';//another chunk of data has been received, so append it to `str`
response.on('data',function(chunk){
str += chunk;});//the whole response has been received, so we just print it out here
response.on('end',function(){console.log(str);});}
http.request(options, callback).end();
const http =require('http');
http.createServer((request, response)=>{const{ headers, method, url }= request;let body =[];
request.on('error',(err)=>{console.error(err);}).on('data',(chunk)=>{
body.push(chunk);}).on('end',()=>{
body =Buffer.concat(body).toString();// BEGINNING OF NEW STUFF
response.on('error',(err)=>{console.error(err);});
response.statusCode=200;
response.setHeader('Content-Type','application/json');// Note: the 2 lines above could be replaced with this next one:// response.writeHead(200, {'Content-Type': 'application/json'})const responseBody ={ headers, method, url, body };
response.write(JSON.stringify(responseBody));
response.end();// Note: the 2 lines above could be replaced with this next one:// response.end(JSON.stringify(responseBody))// END OF NEW STUFF});}).listen(8080);