You and I can click this link and get an inspirational quote. https://zenquotes.io/api/random
Making a call to the same url from within a Blazor WebAssembly give CORS errors.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at...
My test case is the default Visual Studio 2022, add new project Blazor WebAssembly App template. The project comes with a few pages, and some shared components. I modified the SurveyPrompt.razor
shared component to look like the following.
Why can I get the data from the browser using the link, but not from within the app? And most importantly... how do I fix it?
@inject HttpClient http
<div class="alert alert-secondary mt-4">
<p>
<span class="oi oi-pencil me-2" aria-hidden="true"></span>
<strong>@Title</strong></p>
@if (HTML is not null)
{
@((MarkupString)HTML)
}
</div>
@code {
// Demonstrates how a parent component can supply parameters
[Parameter]
public string? Title { get; set; }
private string? HTML { get; set; }
protected override async Task OnInitializedAsync()
{
await GetQuote();
}
private async Task GetQuote()
{
try
{
string url = "https://zenquotes.io/api/random";
var response = await http.GetFromJsonAsync<QuoteResponse>(url);
HTML = response is not null ? response[0]?.h ?? string.Empty : string.Empty;
}
catch (Exception e)
{
HTML = e.Message;
}
}
class QuoteResponse
{
public string? q { get; set; }//quote
public string? a { get; set; }//author
public string? i { get; set; }//author image
public int? c { get; set; }//char count
public string? h { get; set; }//html
}
}
Why can I get the data from the browser using the link, but not from within the app?
Because that API does not provide a CORS header. Either on purpose or because of neglect. It looks like an old service, might be from before CORS was common.
Without that header the Browser blocks the request from your App.
... how do I fix it?
By using a Server. Either Blazor Server-side or your own API server (like Blazor Wasm Hosted).
The code that makes the request should run outside the Browser.
Or lobby with the owners of that site to allow CORS requests.