Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

nodejs request

var request = require('request');
var options = {
    method: 'POST',
    uri: 'https://onfleet.com/api/v2/workers',
    body: '{"name":"Marco Emery","image":"http://cdn3.addy.co/images/marco.png","phone":"415-342-0112","teams":["0pgyktD5f3RpV3gfGZn9HPIt"],"vehicle":{"type":"CAR","description":"Tesla Model 3","licensePlate":"CA 2LOV733","color":"purple"}}',
    headers: {
        'Authorization': 'Basic ' + new Buffer("c64f80ba83d7cfce8ae74f51e263ce93:").toString('base64')
    }
};
request(options, function(error, response, body) {
    console.log(body);
});
Comment

node js http request

// Importing https module
const http = require('http');
  
// Setting the configuration for
// the request
const options = {
    hostname: 'jsonplaceholder.typicode.com',
    path: '/posts',
    method: 'GET'
};
    
// Sending the request
const req = http.request(options, (res) => {
    let data = ''
     
    res.on('data', (chunk) => {
        data += chunk;
    });
    
    // Ending the response 
    res.on('end', () => {
        console.log('Body:', JSON.parse(data))
    });
       
}).on("error", (err) => {
    console.log("Error: ", err)
}).end()
Comment

http node

var fs  = require("fs")
var http  = require("http")

//in this example, I try to show an image
http.createServer((req, res) => {

    fs.readFile(`./images/${req.url}.jpg`, (err, data) => {
        if(err) {
            res.writeHead(404, {'Content-Type': 'text/plain'})
            res.end('Img not found')
        } else {
            res.writeHead(200, {'Content-Type': 'image/jpg'})
            res.end(data)
        }
    })
//change 3000 if you prefer
}).listen(1337, 'localhost')
Comment

http request node.js

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();
Comment

node js do request

let request = require('request')

const formData = {
  // Pass a simple key-value pair
  my_field: 'my_value',
  // Pass data via Buffers
  my_buffer: Buffer.from([1, 2, 3]),
  // Pass data via Streams
  my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
  // Pass multiple values /w an Array
  attachments: [
    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-data
  custom_file: {
    value:  fs.createReadStream('/dev/urandom'),
    options: {
      filename: 'topsecret.jpg',
      contentType: 'image/jpeg'
    }
  }
};
request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
  if (err) {
    return console.error('upload failed:', err);
  }
  console.log('Upload successful!  Server responded with:', body);
});
Comment

nodejs http

const http = require('http')

const server = http.createServer((req, res) => {
  if (req.url === '/') { //Home Page
    res.end('Welcome to our home page')
  } else if (req.url === '/about') { //About page
    res.end('Here is our short history')
  } else {
    res.end(`
    <h1>Oops!</h1>
    <p>We can't seem to find the page you are looking for</p>
    <a href="/">back home</a>
    `) // Page not found
  }
})

server.listen(5000)
console.log('Server is listening on port 5000')
Comment

node http request

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);
Comment

Get Request Node HTTP

const https = require('node:https');

https.get('https://encrypted.google.com/', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });

}).on('error', (e) => {
  console.error(e);
});
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript conditional ? : 
Javascript :: redirect all routes to main component vue 
Javascript :: remove elements from map javascript 
Javascript :: mongoos populate a ref 
Javascript :: 9 + 10 
Javascript :: count items in json 
Javascript :: pass parameter to javascript function onclick 
Javascript :: how to use promise.all 
Javascript :: sort string mixed with numbers javascript 
Javascript :: Angular patchValue dynamically 
Javascript :: node js install aws-sdk 
Javascript :: debug javascript in chrome 
Javascript :: react js and graphql integration 
Javascript :: decode jwt token nodejs 
Javascript :: javascript debugger 
Javascript :: props in classes 
Javascript :: grouped bar charts in chart js 
Javascript :: jquery parse url parameters 
Javascript :: node js login and registration 
Javascript :: initialize set with array javascript 
Javascript :: regex number 
Javascript :: javascript function with parameters 
Javascript :: how to decode jwt token in angular 
Javascript :: prototype chain in javascript 
Javascript :: paper in material ui 
Javascript :: fibonacci recursive method 
Javascript :: javascript repeat function 
Javascript :: javascript create string of given length 
Javascript :: javascript callbacks anonymous function 
Javascript :: create javascript map 
ADD CONTENT
Topic
Content
Source link
Name
7+1 =