2015-11-04 81 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); 
      } 
    });