将curl选项传递给节点js http请求

时间:2015-11-04 14:03:20

标签: javascript node.js api http curl

我有一个关于api的curl请求,需要-u参数来设置用户名登录,而-d用于发送帖子的数据。

这是一个模板:

$ curl -i -X POST "https://onfleet.com/api/v2/workers" \
     -u "c64f80ba83d7cfce8ae74f51e263ce93:" \
     -d '{"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"}}'

如何将-u和-d转换为以这种方式格式化的节点js请求?

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

或者,是否可以使用我可以提供给我的网络浏览器的网址来考虑这些选项?

2 个答案:

答案 0 :(得分:4)

从API文档中,它使用基本的HTTP Auth,其中键字符串是请求的用户名,密码为空。因此,每个请求都必须包含该Authorization标头。您可以使用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);
});

答案 1 :(得分:1)

您可以使用superagent npm模块执行此操作:

var request = require('superagent');
request
   .post('https://onfleet.com/api/v2/workers')
   .auth('c64f80ba83d7cfce8ae74f51e263ce93', '')
   .send({"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"}})
   .end(function(err, res){
         if (res.ok) {
             console.log('yay got ' + JSON.stringify(res.body));
          } else {
             console.log('Oh no! error ' + res.text);
          }
   });