moskalenko2k24
moskalenko2k24

Reputation: 299

How to use React with Web API?

I want to make some project, with frontend on React & backend on ASP.NET Core. I want, that when I develop it uses node server, but also I want to have possibility to build it as one project(API will on /api route, and client will be on root).

I read this https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-6.0?view=aspnetcore-6.0 And they write, that

The startup code for the ASP.NET Core app no longer needs any single-page app-specific logic. The logic for starting the front-end development server during development is injecting into the app at runtime by the new Microsoft.AspNetCore.SpaProxy package.

I created new web project(dotnet new web). Add Microsoft.AspNetCore.SpaProxy package. But it can't find UseSpa extension method. What's the problem or maybe it's better way to do what I want ?

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.SpaProxy;
    
    var builder = WebApplication.CreateBuilder(args);
    var app = builder.Build();
    
    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "../giftbox-front";
    
        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
    app.MapPost("/api/submit", () => "Submit");
    app.Run();

Almost solved it. Add package Microsoft.AspNetCore.SpaServices.Extensions. And wrote

using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseSpa(spa =>
{
    spa.Options.SourcePath = "../giftbox-front";

    if (app.Environment.IsDevelopment())
    {
        spa.UseReactDevelopmentServer(npmScript: "start");
    }
});
app.MapPost("/api/submit", () => "Submit");
app.Run();

It works, I see frontend in browser, but the problem is in my API. When I make request to /api/submit(I change MapPost to MapGet to test it in browser directly) it doesn't return anything. Looks like React server takes my request. How can I fix it ?

Upvotes: 1

Views: 920

Answers (1)

Ruikai Feng
Ruikai Feng

Reputation: 11631

refered this link:How to return 404 on wrong API url? (ASP.NET Core + SPA)

try as below to avoid the request prefixed with /api been taken by server,and see if there're any other errors.

app.MapWhen(x => !x.Request.Path.Value.StartsWith("/api"), builder =>
{
    builder.UseSpa(spa=>
    {
        .....
    });
});

Upvotes: 2

Related Questions