我想在我的react组件中显示数据,但是当我设置API时,react不起作用。似乎中间件设置错误,或者我不了解.net核心和反应的方式。我知道我基本上使用.net核心运行两个不同的应用程序并做出反应,但是有人可以告诉我如何解决我的问题,只需将此API数据放入react页面?我首先是使用实体框架通过方法模型实现的。
我试图更改中间件,但最后总是显示API。当我更改API的路由时,react可以正常工作,因此一切都可以设置为react。但是当他们两个在同一条路线上时。我只看到来自API的数据。而且我只想从.net核心获取数据并将其显示在react组件中。
UsersController.cs
[Route("[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly MafiaContext _context;
public UsersController(MafiaContext context)
{
_context = context;
}
// GET: Users
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> GetUsers()
{
return await _context.Users.ToListAsync();
}
app.js
<Layout>
<Route exact path="/" component={Home} />
<Route path="/users" component={User} /> //this one is a route for the api
<Route path="/counter" component={Counter} />
<Route path="/fetch-data" component={FetchData} />
</Layout>
Startup.cs
公共类启动 { 公共启动(IConfiguration配置) { 配置=配置; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<MafiaContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
}