CodexBloom - Programming Q&A Platform

Azure Static Web Apps with React and Azure Functions: CORS Issues and Build Failures

👀 Views: 65 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
azure react cors azure-functions JavaScript

I'm not sure how to approach I'm currently working on an Azure Static Web App that serves a React frontend and uses Azure Functions as a backend. Everything seems to be set up correctly, but I'm running into CORS issues when trying to call my Azure Functions from the React app. Here's the relevant code from my `function.json` for the Azure Function: ```json { "bindings": [ { "type": "httpTrigger", "direction": "in", "authLevel": "function", "methods": ["get", "post"], "route": "api/myfunction" }, { "type": "httpOut", "direction": "out" } ] } ``` In my React app, I'm making the API call like this: ```javascript fetch(`${process.env.REACT_APP_API_URL}/api/myfunction`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(result => console.log(result)) .catch(behavior => console.behavior('behavior calling API:', behavior)); ``` The question arises when I receive the following behavior in the browser console: `Access to fetch at 'https://<your-function-app>.azurewebsites.net/api/myfunction' from origin 'https://<your-static-web-app>.azurestaticapps.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` I've checked the Azure portal settings for CORS in the Function App and added my static web app URL to the allowed origins. I also tried using the `cors` settings in the `host.json`: ```json { "version": "2.0", "extensions": { "http": { "routePrefix": "api", "customHeaders": { "Access-Control-Allow-Origin": "*" } } } } ``` Despite this, I still encounter CORS issues. Additionally, when trying to build my static web app with Azure DevOps, I receive an behavior about missing dependencies, which I suspect might be related to the way I'm referencing my environment variables. I've tried adjusting my build configuration without success. Any insights on how to resolve the CORS issues and the build failures would be greatly appreciated. Am I approaching this the right way?