简体   繁体   中英

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. But I am new to Node JS so I do not know where to begin. Here is the link to the API documentation: Harvest API Documentation

API requires all the calls to be authenticated how can I work around that?

Thank you in Advance

You can parse using JSON.parse(data) to get the JSON Object

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM