2015-11-04 28 views
2

我对api发出curl请求,需要使用-u参数设置用户名登录,并使用-d发送帖子的数据。将curl选项传递给节点js http请求

这是一个模板:

$ 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' 
}; 

或者,有可能有一个网址,我可以给我的网页浏览器,将采取这些选项考虑?

+0

你试过[节点卷曲(HTTPS://www.npmjs .com/package/node-curl)? **' - u'**可以由基本授权标题取代。 例如:'Authorization:Basic c64f80ba83d7cfce8ae74f51e263ce93:' –

回答

4

从API文档中,它使用基本HTTP身份验证,其中密钥字符串是请求的用户名,密码为空。所以你必须为每个请求提供授权标题。你可以使用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); 
}); 
+0

是的,这就是我需要的!谢谢 :) –

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