Excel插件调用unstructured.io API遭遇CORS问题求解决
Excel插件调用Unstructured.io API时的CORS问题求助
我是CORS相关概念的新手,开发Excel插件时尝试调用unstructured.io API,但每次Axios请求都提示网络错误,查看Excel网络日志后确认问题源于CORS。
我曾用CORS Anywhere搭建代理服务器,通过Curl/Postman测试可正常运行,但在Excel插件中使用该代理时仍出现相同的网络错误,且几乎没有错误信息。我还尝试为localhost配置SSL证书,通过HTTPS访问代理,初步猜测代理未成功绕过CORS,但不确定其他解决方法。
相关代码
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); } }
Flask代理服务器代码
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)
错误提示
Access to XMLHttpRequest at
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.
恳请提供解决思路或建议。
内容的提问来源于stack exchange,提问作者AG1116
相关产品推荐
相关产品推荐

