React front is on 3000 and my ASP.NET Core backend is on port 5000. React part has product definition and data fetching from localhost:5000/api
and accessing data by prevState
in AddProduct
function. Based on the tutorial, I have cors to program.cs
but I cannot make it work. When running the application, I get
This localhost page can't be found error 401.
Product.tsx
export interface Product { id: number; name: string; description: string; price: number; pictureUrl: string; type?: string; brand: string; quantityInStock?: number;}
App.tsx
import { useEffect, useState } from 'react';import { Product } from './product';function App() { const [products,setProducts] = useState<Product[]>([]); useEffect(() => { fetch('htttp://localhost:5000/api/products') .then(response => response.json()) .then(data => setProducts(data)) },[]) function addProduct() { setProducts(prevState => [...prevState, { id: prevState.length + 101, name: "product" + (prevState.length + 1), price: (prevState.length * 100) + 100, brand: 'some brand', description: 'some description', pictureUrl: 'http://picsum.photos/200', }])} return (<div className="app"><h1>RESTORE</h1><ul> {products.map(product=>(<li key={product.id}>{product.name} - {product.price}</li> ))}</ul><button onClick={addProduct}>Add product</button></div> );}export default App;
Program.cs
:
using API.Data;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Migrations.Operations;internal class Program{ private static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddDbContext<StoreContext>(opt => { opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")); }); builder.Services.AddCors(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseCors(opt => { opt.AllowAnyHeader().AllowAnyMethod().WithOrigins("http:/localhost:3000"); }); app.UseAuthorization(); app.MapControllers(); var scope = app.Services.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<StoreContext>(); var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>(); try { context.Database.Migrate(); DBInitializer.Initilize(context); } catch (Exception ex) { logger.LogError(ex, "A problem occurred during migration"); } app.Run(); }}
I have tried to check if my Cors correctly written and if referenced local port are correct.