Category Archives: CORS

Blazor and the GetFromJsonAsync exception TypeError: Failed to Fetch

I have an Azure hosted web api. I also have a simple Blazor standalone application that’s meant to call the API to get a list of categories to display. i.e. the Blazor app is meant to call the Azure web api, fetch the data and display it – should be easy enough, right ?

The web api can easily accessed via a web browser or a console app using the .NET HttpClient, but the Blazor code using the following simply kept throwing exception with the cryptic message “TypeError: Failed to Fetch”

@inject HttpClient Http

// Blazor and other code

protected override async Task OnInitializedAsync()
{
   try
   {
      _categories = await Http.GetFromJsonAsync<string[]>("categories");
   }
   catch (Exception e)
   {
      Debug.WriteLine(e);
   }
}

What was happening is I was actually getting a CORS error, sadly not really reported via the exception so no exactly obvious.

If you get this error interacting with your web api via Blazor then go to the Azure dashboard. I’m running my web api as a container app, type CORS into the left search bar of the resource (in my case a Container App). you should see the Settings section CORS subsection.

Add * to the Allowed Origins and click apply.

Now your Blazor app should be able to interact with the Azure web api app.

Spring boot and CORS

A while back I wrote a post Building a REST service with Spring and today I needed to try out the CORS support to allow a similar Spring based REST service to allow for CORS access from a React application I’m working on.

It’s super easy to allow access to all clients by simply adding @CrossOrigin to your controller, for example

package demo;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin
@RestController
public class SampleController {

    @RequestMapping("/purchaseOrder")
    public PurchaseOrderType getPurchaseOrder() {
        return new PurchaseOrderType(1234);
    }
}

Equally we can just add the same annotation to REST methods instead of the whole controller, for example

@CrossOrigin
@RequestMapping("/purchaseOrder")
public PurchaseOrderType getPurchaseOrder() {
   return new PurchaseOrderType(1234);
}

Note: @CrossOrigin is the equivalent of @CrossOrigin(origins = “*”).

If we want to limit the origins then we simply use the following instead

@CrossOrigin(origins = "http://localhost:3000")

// or an array of origins like this

@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:3001"})