Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve "TypeError: Failed to fetch" error on Blazor?

I am trying to send an HTTP request from my Blazor app to my ASP.NET Core API. I have breakpoints everywhere. The application gives an exception right after the action method on the API controller returns. I am familiar with .NET overall, however, I could not decipher the error message.

Blazor http call:

var response = await _httpClient.GetStreamAsync($"Customer/GetAllCustomers");

ASP.NET Core API Controller action:

[HttpGet]
[Route("GetAllCustomers")]
public async Task<IEnumerable<Customer>> GetAllCustomersAsync()
{
    return await _service.GetAllCustomersAsync();
}

Error stack:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: TypeError: Failed to fetch
WebAssembly.JSException: TypeError: Failed to fetch
  at System.Net.Http.WebAssemblyHttpHandler.doFetch (System.Threading.Tasks.TaskCompletionSource`1[TResult] tcs, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x301ab40 + 0x00a30> in <filename unknown>:0 
  at System.Net.Http.WebAssemblyHttpHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2ff3590 + 0x00174> in <filename unknown>:0 
  at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2ff1e98 + 0x00160> in <filename unknown>:0 
  at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2fc8a98 + 0x00182> in <filename unknown>:0 
  at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) <0x301ff08 + 0x00134> in <filename unknown>:0 
  at System.Net.Http.HttpClient.FinishGetStreamAsync (System.Threading.Tasks.Task`1[TResult] getTask) <0x2ffa720 + 0x000cc> in <filename unknown>:0 
  at WebClient.Services.LectureVideoService.GetAllLectureVideos (Content.Data.Enums.LessonType lessonType) [0x00040] in D:\AlbidersSoftware\CSharp\Albiders Content MS\Albiders\WebClient\Services\LectureVideoService.cs:21 
  at WebClient.Pages.MathAccList.OnInitializedAsync () [0x00026] in D:\AlbidersSoftware\CSharp\Albiders Content MS\Albiders\WebClient\Pages\MathAccList.razor:18 
  at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync () <0x2bed718 + 0x0013a> in <filename unknown>:0 
  at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x2e3a0b0 + 0x000b6> in <filename unknown>:0 
like image 859
M. Azyoksul Avatar asked Dec 01 '20 04:12

M. Azyoksul


People also ask

How do you authenticate in Blazor?

To create a new Blazor WebAssembly project with an authentication mechanism: After choosing the Blazor WebAssembly App template in the Create a new ASP.NET Core Web Application dialog, select Change under Authentication. Select Individual User Accounts to use ASP.NET Core's Identity system.

What is Blazor error UI?

The blazor-error-ui element is normally hidden due to the presence of the display: none style of the blazor-error-ui CSS class in the site's stylesheet ( wwwroot/css/site. css for Blazor Server or wwwroot/css/app. css for Blazor WebAssembly). When an error occurs, the framework applies display: block to the element.

What browsers support Blazor?

Your Blazor WASM application will run fine on Chrome, Edge, Firefox, Safari and also on the mobile variants of these. However, Internet Explorer doesn't support WASM and therefore can't run client-side Blazor apps. If this is important for your case, then you can still use Blazor server-side.

How do I fix TypeError failed to fetch?

To solve the "TypeError: Failed to fetch", make sure to pass the correct configuration to the fetch method, including the URL, HTTP method and headers, and verify that the server you're making a request to is setting the correct CORS headers with the response.

What happens when a code fails in Blazor server?

Otherwise, the failing code results in an unhandled exception that's fatal to a Blazor Server circuit. By default, calls to InvokeAsync must complete within a certain period or else the call times out. The default timeout period is one minute.

Why do I get an error in fetch()?

An incorrect or incomplete URL has been passed to the fetch () method. The server you are making a request to does not send back the correct CORS headers. A wrong protocol is specified in the url. A wrong method or headers have been passed to the fetch () method. Here's an example of how the error occurs.

How does Blazor manage unhandled exceptions?

This article describes how Blazor manages unhandled exceptions and how to develop apps that detect and handle errors. When a Blazor app isn't functioning properly during development, receiving detailed error information from the app assists in troubleshooting and fixing the issue.


2 Answers

Unhandled exception rendering component: TypeError: Failed to fetch

WebAssembly.JSException: TypeError: Failed to fetch

I did a test to make request(s) from my Blazor WebAssembly app to action method with testing data, which works well on my side.

[Route("[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
    [HttpGet]
    [Route("GetAllCustomers")]
    public async Task<IEnumerable<Customer>> GetAllCustomersAsync()
    {
        //for testing purpose

        return new List<Customer> { new Customer { Id = 1, Name = "Test1" }, new Customer { Id = 2, Name = "Test2" } };

        //return await _service.GetAllCustomersAsync();
    }
}

GetAllCustomers.razor

@page "/getallcustomers"
@using BlazorWasmApp1.Shared
@inject HttpClient _httpClient

<h3>Customer List</h3>

@if (customers == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var customer in customers)
            {
                <tr>
                    <td>@customer.Id</td>
                    <td>@customer.Name</td>
                </tr>
            }
        </tbody>
    </table>
}


@code {
    private Customer[] customers;

    protected override async Task OnInitializedAsync()
    {
        //call external API
        //_httpClient.BaseAddress = new Uri("https://localhost:44312/");


        //your API action would return a collection of Customer
        //you can try to call .GetFromJsonAsync<Customer[]>() to get the expected data
        //rather than get stream
        customers = await _httpClient.GetFromJsonAsync<Customer[]>($"Customer/GetAllCustomers");
    }
}

Test Result

enter image description here

To troubleshoot the issue, please try:

  1. check the URL of your request in browser developer tool Network tab, and make sure you are making request to correct endpoint

  2. if your ASP.NET Core Web API project is hosting on separate site, please make sure you configured and enabled CORS to allow request(s) from your Blazor WebAssembly app, and make sure that API is running

like image 96
Fei Han Avatar answered Nov 12 '22 14:11

Fei Han


Also check if your api is requesting from HTTP, change it to https: it will work

enter image description here

like image 35
Cris M Avatar answered Nov 12 '22 13:11

Cris M