2016-07-02 12 views
0

es ist mir wieder mit einer anderen lahmen Frage. Ich habe den folgenden Aufruf einen Rattic Passwort-Datenbank-API, die ordnungsgemäß funktioniert:cURL Aufruf an API in NodeJS Anfrage

curl -s -H 'Authorization: ApiKey myUser:verySecretAPIKey' -H 'Accept: text/json' https://example.com/passdb/api/v1/cred/\?format\=json 

Ich habe versucht, diesen Aufruf in NodeJS zu replizieren, jedoch gibt folgende Formel leer:

var request = require('request'); 

url='https://example.com/passdb/api/v1/cred/?format=json'; 

request({ 
    url: url, 
    method: 'POST', 
    headers: [ 
     { 'Authorization': 'ApiKey myUser:verySecretAPIKey' } 
    ], 
    }, 
    function (error, response, body) { 
     if (error) throw error; 
     console.log(body); 
    } 
); 

Jede Hilfe sehr geschätzt wird.

+1

Haben Sie versucht mit 'GET'? –

+0

Yup, Körpervariable ist immer noch eine leere Zeile (nicht null oder undefiniert):/ – Neekoy

Antwort

1
  • Wie bereits in den Kommentaren aus, verwenden GET, nicht POST;
  • headers sollte ein Objekt sein, kein Array;
  • Sie fügen die Accept Kopfzeile nicht hinzu.

Alle kombiniert, versuchen Sie dies:

request({ 
    url  : url, 
    method : 'GET', 
    headers : { 
    Authorization : 'ApiKey myUser:verySecretAPIKey', 
    Accept  : 'text/json' 
    }, function (error, response, body) { 
    if (error) throw error; 
    console.log(body); 
    } 
}); 
+0

Meine Curl-Anfrage enthält Daten __- d phonenumber = 07XXXXXXX__ wie kann ich das zur Anfrage hinzufügen –

+0

@IzzoObella mit der 'body' Option – robertklep

1

Header sollten ein Objekt sein.

var request = require('request'); 

url='https://example.com/passdb/api/v1/cred/?format=json'; 

request({ 
      url: url, 
      method: 'POST', 
      headers: { 
       'Authorization': 'ApiKey myUser:verySecretAPIKey' 
      } 
     }, function (error, response, body) { 
      if (error) throw error; 
      console.log(body); 
     }); 
1

Eine Sache, die Sie tun können, eine Locke Anfrage in Postman importieren und dann in verschiedene Formen exportieren. Beispiel: nodejs:

var http = require("https"); 

var options = { 
    "method": "GET", 
    "hostname": "example.com", 
    "port": null, 
    "path": "/passdb/api/v1/cred/%5C?format%5C=json", 
    "headers": { 
    "authorization": "ApiKey myUser:verySecretAPIKey", 
    "accept": "text/json", 
    "cache-control": "no-cache", 
    "postman-token": "c3c32eb5-ac9e-a847-aa23-91b2cbe771c9" 
    } 
}; 

var req = http.request(options, function (res) { 
    var chunks = []; 

    res.on("data", function (chunk) { 
    chunks.push(chunk); 
    }); 

    res.on("end", function() { 
    var body = Buffer.concat(chunks); 
    console.log(body.toString()); 
    }); 
}); 

req.end();