[英]Routing from an angular front end to an asp.net core 3.1 backend
所以這是我的 backend.csproj 。 我在 angular 中做一個前端 spa,連接到我在 memory 數據庫中的后端。 我可以從我的后端應用程序的 URL 連接到我的數據庫,如圖所示。 我也可以提出 postman 請求並通過此header獲得postman 成功響應......到目前為止一切都很好。 在我的前端有一個問題。 我有我的前端 angular服務 package 和 url 我在 Z03D476861AFD388411510 F 中使用。 在我的組件中,我調用此方法來連接到我的服務。 不知何故,當我在 postman 中執行獲取請求時,我無法獲得“旅行”列表。 我幾乎 80% 確定錯誤在后端,因為我可以在其他后端應用程序中獲取請求。 所以我要把我的后端代碼放在這里。
我的程序.cs
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
using (var context = scope.ServiceProvider.GetService<AppDbContext>())
{
context.Database.EnsureCreated();
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
我的啟動.cs
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddControllers().ConfigureApiBehaviorOptions(options =>
{
});
services.AddDbContext<AppDbContext>(options =>
{
options.UseInMemoryDatabase(Configuration.GetConnectionString("memory"));
});
services.AddScoped<ITripRepository, TripRepository>();
services.AddScoped<ITripService, TripService>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddAutoMapper(typeof(Startup));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
我得到 controller:
[HttpGet]
[ProducesResponseType(typeof(List<TripDTO>), 200)]
public async Task<IEnumerable<TripDTO>> GetAllAsync()
{
var trips = await _tripService.ListAsync();
var dtos = _mapper.Map<IEnumerable<Trip>, IEnumerable<TripDTO>>(trips);
return dtos;
}
編輯:當我在我試圖獲取的列表中執行前端 console.log 時出現的錯誤是在此處輸入圖像描述
EDIT2:AppDbContext 后端
public class AppDbContext : DbContext
{
public DbSet<Trip> Trips { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Trip>().ToTable("Trips");
builder.Entity<Trip>().HasKey(p => p.Id);
builder.Entity<Trip>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();
builder.Entity<Trip>().Property(p => p.Key).IsRequired().HasMaxLength(10);
builder.Entity<Trip>().Property(p => p.IsEmpty).IsRequired();
builder.Entity<Trip>().Property(p => p.Orientation).IsRequired();
builder.Entity<Trip>().Property(p => p.LineKey).IsRequired().HasMaxLength(10);
builder.Entity<Trip>().Property(p => p.PathKey).IsRequired().HasMaxLength(10);
builder.Entity<Trip>().Property(p => p.IsGenerated).IsRequired();
builder.Entity<Trip>().Property(p => p.PassingTimes)
.HasConversion(
v => JsonConvert.SerializeObject(v),
v => JsonConvert.DeserializeObject<List<PassingTime>>(v));
builder.Entity<Trip>().HasData
(
new Trip { Id = 100,Key="Trip:344",IsEmpty=false,Orientation=false,LineKey="Line:444",PathKey="Path:344",IsGenerated=true }, // Id set manually due to in-memory provider
new Trip { Id = 1200,Key="Trip:1344",IsEmpty=false,Orientation=false,LineKey="Line:2444",PathKey="Path:3424",IsGenerated=true }
);
}
}
}
編輯 3:
HTML
<!DOCTYPE html>
<html>
<body>
<h4>List of Trips</h4>
<div class="list row">
<div class="col-md-6">
<ul class="list-group">
<li class="list-group-item" *ngFor="let trip of trips; let i = index" [class.active]="i == currentIndex" (click)="setActiveTrip(trip, i)">
{{ trip.key }}
</li>
</ul>
</div>
<div *ngIf="!currentTrip">
<br />
<p>Please click on a trip to see the details...</p>
</div>
<div class="col-md-6">
<div *ngIf="currentTrip">
<h4>Selected Trip Details</h4>
<div>
<div>
<label><strong>Key:</strong></label> {{ currentTrip.key }}
</div>
</div>
</div>
</div>
</div>
</body>
</html>
組件.cs
import { Component, OnInit } from '@angular/core';
import { TripService } from 'src/app/masterdataviagem/services/trip-service';
@Component({
selector: 'app-tripslist',
templateUrl: './tripslist.component.html',
styleUrls: ['./tripslist.component.css']
})
export class TripslistComponent implements OnInit {
trips: any;
currentTrip: any = null;
currentIndex = -1;
key = '';
tripsList:any;
constructor(private tripService:TripService) { this.tripsList=this.tripService.getAll()}
ngOnInit(): void {
this.retrieveTrips();
}
retrieveTrips() {
this.trips= this.tripService.getAll().subscribe(
data => {
this.trips = data;
console.log(data);
},
error => {
console.log(error);
});
console.log(this.trips);
}
refreshList() {
this.retrieveTrips();
this.currentTrip = null;
this.currentIndex = -1;
}
setActiveTrip(trip: any, index: number) {
this.currentTrip = trip;
this.currentIndex = index;
}
}
也許您必須在后端啟用 CORS (我的猜測是瀏覽器控制台末尾的“未知錯誤”,那就是您的 console.log(錯誤))。
您可以嘗試使用此 chrome 擴展程序進行測試: https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en 。
如果您的后端響應顯示啟用了擴展,那么您必須啟用 CORS:
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#ecors
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.