簡體   English   中英

將curl選項傳遞給Node JS HTTP請求

[英]Pass curl options to node js http request

我向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'
};

或者,是否可能有一個我可以提供給我的Web瀏覽器的URL來考慮這些選項?

從API文檔開始,它使用基本的HTTP身份驗證,其中密鑰字符串是請求的用戶名,密碼為空白。 因此,每個請求都必須具有那個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);
});

您可以使用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);
          }
   });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM