Reputation: 1
I found some code on this https://learn.microsoft.com/en-us/office/dev/scripts/resources/samples/external-fetch-calls. I amend the code with the URL to read data from SolarEdge for my plant. I changed the ID and API-key for security reasons. Below my code:
async function main(workbook: ExcelScript.Workbook) {
// Get data from SolarEdge server.`
const response = await fetch('https://monitoringapi.solaredge.com/site/123456/details.json?api_key=F6XJXU368WEAEI7CN9O88U6VD1LLTQ56');
const repos: Repository[] = await response.json();
// Create an array to hold the returned values.
const rows: (string | boolean | number)[][] = [];
// Convert each repository block into a row.
for (let repo of repos) {
rows.push([repo.id, repo.name, repo.license?.name, repo.license?.url])
}
// Add the data to the current worksheet, starting at "A2".
const sheet = workbook.getActiveWorksheet();
const range = sheet.getRange('A2').getResizedRange(rows.length - 1, rows[0].length - 1);
range.setValues(rows);
}
// An interface matching the returned JSON for repository.
interface Repository {
name: string,
id: string,
license?: License
}
// An interface matching the returned JSON for a repo license.
interface License {
name: string,
url: string
}
When I run this script in Excel Online the following error comes up:
Line 3: NetworkError when attempting to fetch resource.
What do I need to change to make this script read the data from SolarEdge?
When I run the URL in either browser I'm getting the JSON back and can read the data. And also using Postman results in getting data in a JSON string.
Upvotes: 0
Views: 633
Reputation: 1581
I guess this is most likely caused by the CORS issue, which could block you from making web requests from the current domain (where Office Scripts is running) to a different domain (monitoringapi.solaredge.com
).
You can confirm it by looking at the Console tab of the browser DevTools (F12
for Chrome/Edge) when running your script. If there is any error like "Access to fetch at ... from origin ... has been blocked by CORS policy...", then that could be the case.
I tried myself with some test script making fetch
calls to the monitoringapi.solaredge.com
endpoint and was indeed seeing the CORS error on the Console tab.
Here are some potential workaround ideas. Basically, if you don't have control over the API service provider (in your case the SolarEdge) to make changes to the APIs to support CORS on their server side, you'll need to find a way to "bridge" your requests through some sort of middle-tier or proxy service.
Upvotes: 1