Reputation: 69
I have a frontend client in Next.js 13.2.3 and a backend in ASP.NET Web API (both saved locally on my pc, they are different projects). The backend API works fine because i can see requests going in/out with the help of Swagger UI. I can also perfectly fetch https://jsonplaceholder.typicode.com/users from my Next.js app.
The issue arises when I try fetching my backend API from the frontend. I have updated my CORS in the backend to allow http://127.0.0.1:3000 (which is where the frontend gets served). I know the backend is not an issue because this worked out with my other React.js project using Vite.
This is my ASP.NET Web API Program.cs file with CORS where the "frontend-url" is saved in appsettings.Development.json file:
using Microsoft.EntityFrameworkCore;
using PropertyManagerWebAPI.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
#region Set up Cors policy to be able to to talk to React client
var provider = builder.Services.BuildServiceProvider();
var configuration = provider.GetRequiredService<IConfiguration>();
builder.Services.AddCors(options =>
{
var frontendUrl = configuration.GetValue<string>("frontend_url");
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins(frontendUrl).AllowAnyMethod().AllowAnyHeader();
});
});
#endregion
//Dependency Injection of DbContext Class
builder.Services.AddDbContext<APIDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DevConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.Run();
This is my Next.js, and the path of my page.tsx file : src\app\dashboard\page.tsx
async function getData() {
const response = await fetch("https://127.0.0.1:7227/api/Properties")
if (!response.ok) {
throw new Error('Failed to fetch data');
}
return response.json()
}
export default async function ProductsPage() {
const a: any = await getData()
return (
<>
<div>
{a.map((info: any) =>
<div key={info.id}>
{info.city}
</div>
)}
</div>
</>
)
}
This is the error that is thrown in the browser:
Uncaught TypeError: fetch failed
at Object.fetch (C:\Users\bob\Desktop\all_important\myproject\node_modules\.pnpm\[email protected]_biqbaboplfbrettd7655fr4n2y\node_modules\next\dist\compiled\undici\index.js:1:26686)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
The above error occurred in the <RedirectErrorBoundary> component:
at RedirectErrorBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:361:9)
at RedirectBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:368:11)
at NotFoundBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:404:11)
at LoadingBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:317:11)
at ErrorBoundaryHandler (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/error-boundary.js:59:9)
at ErrorBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/error-boundary.js:72:11)
at RenderFromTemplateContext (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/render-from-template-context.js:12:34)
at OuterLayoutRouter (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:23:11)
at section
at ScrollAndFocusHandler (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:153:1)
at InnerLayoutRouter (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:195:11)
at RedirectErrorBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:361:9)
at RedirectBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:368:11)
at NotFoundErrorBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:397:9)
at NotFoundBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:404:11)
at LoadingBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:317:11)
at ErrorBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/error-boundary.js:72:11)
at RenderFromTemplateContext (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/render-from-template-context.js:12:34)
at OuterLayoutRouter (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/layout-router.js:23:11)
at body
at html
at ReactDevOverlay (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/react-dev-overlay/internal/ReactDevOverlay.js:61:9)
at HotReload (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/react-dev-overlay/hot-reloader-client.js:20:11)
at Router (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/app-router.js:48:11)
at ErrorBoundaryHandler (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/error-boundary.js:59:9)
at ErrorBoundary (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/error-boundary.js:72:11)
at AppRouter (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/components/app-router.js:24:13)
at ServerRoot (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/app-index.js:126:11)
at RSCComponent
at Root (webpack-internal:///(app-client)/./node_modules/.pnpm/[email protected]_biqbaboplfbrettd7655fr4n2y/node_modules/next/dist/client/app-index.js:143:11)
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundaryHandler.
Could this be a server issue, where I am hosting two things on the same localhost?
I've looked through the docs but there is nothing about fetching from localhost servers. Everything works fine if you substitute the localhost URL with a "https://jsonplaceholder.typicode.com/users" and change the parameters to the respectable key-value pair that they have. I have also tried creating a new Next.js project with npm instead of pnpm but this did not change anything.
Upvotes: 3
Views: 4581
Reputation: 69
So after @Sebastien Castiel mentioned the "https" part, I used a try-catch block on the fetch request to see the extended error source and found this in my console log:
Error: self signed certificate
at TLSSocket.onConnectSecure (node:_tls_wrap:1535:34)
at TLSSocket.emit (node:events:513:28)
at TLSSocket._finishInit (node:_tls_wrap:949:8)
at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:730:12)
at TLSWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
code: 'DEPTH_ZERO_SELF_SIGNED_CERT'}
I looked into nextjs protocols for ssl certificates and found out that they don't provide any certificates when developing locally. Didn't have to face this when I was developing with Vite, seems like Vite automatically assigns certificates when your try to develop using "https". So your choices are:
Option 1. I have not done this yet but you can create a local certificate Calling local dotnet https backend from local NextJS results in FetchError: self-signed certificate. You can do this for MacOS as well here.
Option 2. In your Visual Studio project solution explorer, find a properties folder and go to the launchSettings.json file and comment out the "https" url. You can also place the "http" url before the "https".
{
...
"profiles": {
...
"applicationUrl": "https://localhost:7227;http://localhost:5085",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
In the end it was a great experience, because I learned more about Secure Sockets Layer (SSL) certificates when working with Nextjs.
Upvotes: 1