I am trying to host a vue spa client within my api's wwwroot folder. I have set up build scripts to build the spa into the folder and that works well. I also use app.UseSpa()
to proxy request in case of development. With my current configuration I am able to run the UI and navigate as expected however making calls with fetch('/api/get/data')
only yields a 404 response or the html content of hte index.html
file. I want to be able to make api calls and browse the UI at the same time with this hosted approach.
current Program.cs config using .net7 Minimal API approach with Carter library for endpoint mapping
builder.Services.AddSpaStaticFiles(opts =>
{
opts.RootPath = "wwwroot/app";
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCarter();
....
app.UseCors(opts => { opts.AllowAnyOrigin(); });
app.UseHttpsRedirection();
app.Use((ctx, next) =>
{
if (ctx.Request.Path.StartsWithSegments("/api"))
{
ctx.Response.StatusCode = 404;
return Task.CompletedTask;
}
return next();
});
app.UseSpaStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapCarter();
app.UseSpa(opts =>
{
if (app.Environment.IsDevelopment())
{
opts.UseProxyToSpaDevelopmentServer("http://localhost:5173");
}
});
app.MapFallbackToFile("index.html");
If you are under development environment:
Check your Vue config file
vite.config.js
, look at this document.For example:
Make sure that the
proxy
'starget
is actually pointing to your backend app.If production environment:
The default released web api port is
5000
.Use a reverse proxy server (such as Caddy) redirect to your web api: