簡體   English   中英

使用 Node JS 訪問 API 並將其解析為 JSON 文件

[英]Access API using Node JS and parse it as a JSON file

我正在嘗試從 Harvest API 訪問所有項目並將其解析為 JSON 文件。 但是我是 Node JS 的新手,所以我不知道從哪里開始。 這是 API 文檔的鏈接: Harvest API 文檔

API 要求對所有調用進行身份驗證,我該如何解決?

先感謝您

您可以使用 JSON.parse(data) 進行解析以獲取 JSON 對象

const https = require("https");

const options = {
  protocol: "https:",
  hostname: "api.harvestapp.com",
  path: "/v2/users/me",
  headers: {
    "User-Agent": "Node.js Harvest API Sample",
    Authorization: "Bearer " + process.env.HARVEST_ACCESS_TOKEN,
    "Harvest-Account-ID": process.env.HARVEST_ACCOUNT_ID,
  },
};

https
  .get(options, (res) => {
    const { statusCode } = res;

    if (statusCode !== 200) {
      console.error(`Request failed with status: ${statusCode}`);
      return;
    }

    res.setEncoding("utf8");
    let rawData = "";
    res.on("data", (chunk) => {
      rawData += chunk;
    });
    res.on("end", () => {
      try {
        const parsedData = JSON.parse(rawData);
        console.log(parsedData);
      } catch (e) {
        console.error(e.message);
      }
    });
  })
  .on("error", (e) => {
    console.error(`Got error: ${e.message}`);
  });

請參考

https://github.com/harvesthq/harvest_api_samples/blob/master/v2/harvest_api_sample.js

暫無
暫無

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

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