简体   繁体   English

使用 Node JS 访问 API 并将其解析为 JSON 文件

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

I am trying to access all the projects from Harvest API and parse it as a JSON file.我正在尝试从 Harvest API 访问所有项目并将其解析为 JSON 文件。 But I am new to Node JS so I do not know where to begin.但是我是 Node JS 的新手,所以我不知道从哪里开始。 Here is the link to the API documentation: Harvest API Documentation这是 API 文档的链接: Harvest API 文档

API requires all the calls to be authenticated how can I work around that? API 要求对所有调用进行身份验证,我该如何解决?

Thank you in Advance先感谢您

You can parse using JSON.parse(data) to get the JSON Object您可以使用 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}`);
  });

Please refer请参考

https://github.com/harvesthq/harvest_api_samples/blob/master/v2/harvest_api_sample.js 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