Preface: I’m super new to CORS and this whole concept.
I’m building an Excel add in through which I want to call the unstructured.io api (https://api.unstructured.io/general/v0/general). However, every time I try to make the call, Axios just says there’s been a network error. After looking at network logs in Excel, looks like CORS is the issue.
I tried building a proxy server using CORS anywhere and testing it using Curl/Postman requests and it works great. However, when trying to use this server in the add in, I still run into the same issue where I get a network error, with little error info or anything else, so I’m very lost on what to do. I also tried using the proxy through HTTPS by obtaining an SSL certificate on locahost, etc. My initial guess is that the proxy isn’t bypassing CORS, but not sure how else to do it.
Anyone have any tips/thoughts here?
Code for reference:
taskpane.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Excel Add-in</title>
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="./taskpane.js"></script>
<link rel="stylesheet" type="text/css" href="./taskpane.css">
</head>
<body>
<div id="container">
<div class="content">
<button id="tableButton">Table</button>
<button id="testButton">Test</button>
<select id="documentDropdown" onchange="selectDocument()">
<option value="">Select a document</option>
</select>
<div id="fileContent" style="position: relative;"></div>
<canvas id="selectionCanvas" style="position: absolute; top: 0; left: 0; display: none;"</canvas>
<div id="logArea"></div>
</div>
</div>
</body>
</html>
taskpane.js
Office.onReady(info => {
if (info.host === Office.HostType.Excel) {
try {
document.getElementById('testButton').onclick = test;
} catch (error) {
console.error('Error in Office.onReady:', error);
logMessage(`Error in Office.onReady: ${error.message}`);
}
}
});
function logMessage(message) {
const logArea = document.getElementById('logArea');
if (logArea) {
const logEntry = document.createElement('div');
logEntry.innerHTML = message;
logArea.appendChild(logEntry);
logArea.scrollTop = logArea.scrollHeight;
}
console.log(message);
}
function logAxiosError(error) {
if (error.response) {
logMessage(`Error response data: ${JSON.stringify(error.response.data)}`);
logMessage(`Error response status: ${error.response.status}`);
logMessage(`Error response headers: ${JSON.stringify(error.response.headers)}`);
} else if (error.request) {
logMessage('No response received. Possible network error or CORS issue.');
logMessage('Request data:', JSON.stringify(error.toJSON(), null, 2));
} else {
logMessage(`Axios error message: ${JSON.stringify(error.toJSON(), null, 2)}`);
}
console.error('Detailed extraction error:', error);
}
async function test() {
logMessage("hi");
try {
const response = await axios.get('https://127.0.0.1:5000/process-image', {
headers: {
'Accept': 'application/json'
}
});
if (response.status === 200) {
const jsonResponse = response.data;
logMessage(JSON.stringify(jsonResponse, null, 2)); // Do something with the response
} else {
logMessage(`Error: ${response.status}n${response.statusText}`);
}
} catch (error) {
logAxiosError(error);
}
}
I’ve also created a flask server with Flask and Flask-CORS (Had created a proxy server previously but trying this now) with SSL certificates enabled:
from flask import Flask, jsonify
from flask_cors import CORS
import requests
import pandas as pd
app = Flask(__name__)
CORS(app)
@app.route('/process-image', methods=['GET'])
def process_image():
file_path = 'test.png'
api_key = 'MY-API-KEY'
url = 'https://api.unstructured.io/general/v0/general'
headers = {
'accept': 'application/json',
'unstructured-api-key': f'{api_key}'
}
files = {
'files': (file_path, open(file_path, 'rb'), 'image/jpeg'),
'strategy': (None, 'hi_res'),
}
response = requests.post(url, headers=headers, files=files)
if response.status_code == 200:
data = response.json()
table_data = data[0]['metadata']['text_as_html']
df = pd.read_html(table_data)[0]
return df.to_json(orient='records')
else:
return jsonify({'error': 'Error from Unstructured API', 'status_code': response.status_code, 'response': response.text}), response.status_code
if __name__ == '__main__':
app.run(ssl_context=('cert.pem', 'key.pem'), debug=True)
I’m also pretty sure it’s a CORS error because I get no response data back and when I open up the console in Excel, I get “Access to XMLHttpRequest at <URL> from origin https://localhost:3000 has been blocked by CORS policy: response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
AG1116 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.