“nodejs запросить API” Ответ

nodejs запросить API

const https = require('https');

https.get('https://jsonplaceholder.typicode.com/users', res => {
  let data = [];
  const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date';
  console.log('Status Code:', res.statusCode);
  console.log('Date in Response header:', headerDate);

  res.on('data', chunk => {
    data.push(chunk);
  });

  res.on('end', () => {
    console.log('Response ended: ');
    const users = JSON.parse(Buffer.concat(data).toString());

    for(user of users) {
      console.log(`Got user with id: ${user.id}, name: ${user.name}`);
    }
  });
}).on('error', err => {
  console.log('Error: ', err.message);
});
Hungry Hamerkop

запрос Nodejs

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);
});
Almabek

Узел JS DO запрос

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);
});
Jules

Ответы похожие на “nodejs запросить API”

Вопросы похожие на “nodejs запросить API”

Больше похожих ответов на “nodejs запросить API” по JavaScript

Смотреть популярные ответы по языку

Смотреть другие языки программирования