簡體   English   中英

在NodeJS請求中對API的cURL調用

[英]cURL call to API in NodeJS Request

又是我一個又一個question腳的問題。 我對可以正常運行的Rattic密碼數據庫API進行了以下調用:

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

我試圖在NodeJS中復制此調用,但是以下返回空白:

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

任何幫助表示贊賞。

  • 正如注釋中已經指出的那樣,請使用GET而不是POST
  • headers應該是一個對象,而不是數組;
  • 您沒有添加Accept標頭。

結合起來,試試這個:

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

標頭應該是一個對象。

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

您可以做的一件事是將curl請求導入Postman,然后將其導出為其他形式。 例如,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();

暫無
暫無

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

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