Office任务窗格插件中Axios无法向自建Fast API发送请求问题排查求助
Let's break down why your local FastAPI isn't receiving requests from the Office task pane add-in, even though it works in a vanilla React app and testing tools. Here are the key areas to check and fix:
1. Office Add-in Content Security Policy (CSP) Blocking Requests
Yeoman-generated Office add-ins enforce strict CSP rules by default, which likely block requests to your local 127.0.0.1:8000 endpoint. This is the most common culprit here—if the CSP doesn't explicitly allow your FastAPI address, the browser will silently block the request before it even leaves the client.
Fix:
Open your public/index.html file and update the Content-Security-Policy meta tag to include your FastAPI URL:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' https://appsforoffice.microsoft.com http://127.0.0.1:8000 'unsafe-inline' 'unsafe-eval'">
If you switch your FastAPI to HTTPS (recommended for consistency with the add-in's secure context), replace http:// with https://.
2. Mixed Content Blocking (HTTPS vs HTTP)
Office task pane add-ins run in a secure HTTPS context by default (your webpack config enables HTTPS via getHttpsOptions()). Browsers block mixed-content requests (HTTPS page calling HTTP endpoints) as a security measure—this would explain why no request reaches your FastAPI server.
Fix:
Run your FastAPI with HTTPS to match the add-in's context. Use uvicorn with self-signed certificates:
# Generate self-signed certs (if you don't have them) openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 # Start FastAPI with HTTPS uvicorn main:app --host 127.0.0.1 --port 8000 --ssl-keyfile=./key.pem --ssl-certfile=./cert.pem
You'll need to trust the self-signed certificate in your browser/Office app to avoid security warnings.
3. Function Execution & Promise Handling Issues
Your getPlayground2 function has two problems that could cause silent failures and undefined Promise returns:
- The async function doesn't return the axios Promise, so it resolves to
undefinedimmediately. - Console logs might not show up if you're not using the correct Office add-in debug tools.
Fix:
Rewrite the function to properly handle async/await and return the result:
getPlayground2 = async (name, prompt, engine, purpose, format, max_tokens, temperature, user) => { const configObject = { url: "https://127.0.0.1:8000/completion", // Update to HTTPS if needed method: "post", headers: { "Content-Type": "application/json", Accept: "application/json", }, data: { name, prompt, engine, purpose, format, max_tokens, temperature, user }, }; console.log("playground2 called"); try { const res = await axios.request(configObject); console.log(res.status, res.data); return res.data.choices[0].text; } catch (error) { console.error("API call failed:", error.response || error.message); throw error; // Re-throw to let the caller handle the error } };
4. Verify FastAPI CORS Configuration
While you mentioned checking CORS, make sure your FastAPI has the CORSMiddleware properly configured to allow requests from your add-in's origin (usually https://localhost:3000):
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "https://localhost:3000", # Add your add-in's dev server URL "http://localhost:3000", # Include HTTP if you're testing without HTTPS ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
Note: Webpack devServer CORS headers only apply to requests made to the dev server itself, not to external APIs like your FastAPI.
5. Use Office Add-in Debug Tools to Diagnose
You mentioned not seeing full console logs—Office add-ins have dedicated debug tools that let you inspect network requests and logs properly:
- Open your Office app (e.g., Word) with the task pane add-in loaded.
- Click the three-dot menu in the task pane's top-right corner.
- Select View Source to open Edge DevTools. Here you can:
- Check the Console tab for your
console.logstatements. - Go to the Network tab to see if requests are being sent (and if they're blocked by CSP/mixed content).
- Check the Console tab for your
Final Checks
- Confirm the
getPlayground2function is actually being called: Add a log in the code that triggers this function (e.g., a button click handler) to ensure the event is binding correctly. - If you're using class components, make sure the function is bound to
this(use arrow functions or bind in the constructor).
内容的提问来源于stack exchange,提问作者Jannik

