metanit上有一个基本示例,我已将其简化并尝试重新制作fetch
。
控制器:
using Microsoft.AspNetCore.Mvc;
using ReactWithASP.Server.Models;
namespace ReactWithASP.Server.Controllers
{
[ApiController]
[Route("[controller]")]
public class PhonesController : Controller
{
static readonly List<Phone> data;
static PhonesController()
{
data = new List<Phone>
{
new Phone { Id = Guid.NewGuid().ToString(), Name="iPhone", Price=52000 },
new Phone { Id = Guid.NewGuid().ToString(), Name="Samsung", Price=42000 },
new Phone { Id = Guid.NewGuid().ToString(), Name="Xiaomi ", Price=66600 },
};
}
[HttpGet]
public IEnumerable<Phone> Get()
{
return data;
}
}
}
表现:
import React from 'react';
import './App.css';
class PhonesList extends React.Component {
constructor(props) {
super(props);
this.state = { phones: [] };
}
loadData() {
fetch('phones')
.then(response => response.text())
.then((data) => this.setState({ phones: data }));
}
componentDidMount() {
this.loadData();
}
render() {
return <div>
<h2>List of phones</h2>
<div>
{
this.state.phones
}
</div>
</div>;
}
}
export default PhonesList
数据直接在控制器中定义。需要在启动时将它们拖入视图中。在链接中的原始示例中,它是通过完成的XMLHttpRequest
,但我想使用fetch
。在所呈现的版本中,它返回的不是数据,而是标记index.html
。
程序.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddMemoryCache();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddControllersWithViews();
builder.Services.AddControllers();
var app = builder.Build();
app.UseDefaultFiles();
app.UseStaticFiles();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseDeveloperExceptionPage();app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapDefaultControllerRoute();
app.UseAntiforgery();
app.Run();
在文件夹中的项目中
.client
有一个文件,vite.config.js
您需要在其中找到方法defineConfig()
并设置参数proxy
。