Solution to 'TypeError: Failed to fetch' with ReactJS and Azure Functions

error message

I got this error while trying to call an Azure Function from ReactJS app.

"TypeError: Failed to fetch

\n    at fetchData (http://localhost:3000/static/js/bundle.js:33:32)\n    at http://localhost:3000/static/js/bundle.js:41:5\n    at commitHookEffectListMount (http://localhost:3000/static/js/bundle.js:27074:30)\n    at commitPassiveMountOnFiber (http://localhost:3000/static/js/bundle.js:28567:17)\n    at commitPassiveMountEffects_complete (http://localhost:3000/static/js/bundle.js:28539:13)\n    at commitPassiveMountEffects_begin (http://localhost:3000/static/js/bundle.js:28529:11)\n    at commitPassiveMountEffects (http://localhost:3000/static/js/bundle.js:28519:7)\n    at flushPassiveEffectsImpl (http://localhost:3000/static/js/bundle.js:30404:7)\n    at flushPassiveEffects (http://localhost:3000/static/js/bundle.js:30356:18)\n    at http://localhost:3000/static/js/bundle.js:30171:13"

If you see that it is likely because you don’t have CORS configured.

Add this to local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true"
  },
  "Host": {
    "CORS": "*",
    "CORSCredentials": false,
    "LocalHttpPort": 7071
  }
}

Change 7071 to the port your function is running on.

If that doesn’t work, then make sure you have access to the function. Sometimes you need to configure it for anonymous access in the function.json file

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ],
  "scriptFile": "../dist/HttpTrigger/index.js"
}

See ‘authLevel’ setting above.

Jon