React 应用不显示 ASP.NET Core / EF Core 数据库数据,使用 Cors 访问它们(Neil Cummings 关于 REACT 的教程)

问题描述 投票:0回答:1

React 前端位于 3000,我的 ASP.NET Core 后端位于端口 5000。React 部分具有产品定义和从

localhost:5000/api
获取数据以及通过
prevState
函数中的
AddProduct
访问数据。根据教程,我有
program.cs
的功能,但我无法使其工作。运行应用程序时,我得到

找不到此本地主机页面,错误 401。

产品.tsx

export interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  pictureUrl: string;
  type?: string;
  brand: string;
  quantityInStock?: number;
}

应用程序.tsx

import { useEffect, useState } from 'react';
import { Product } from './product';

function App() {
  const [products,setProducts] = useState<Product[]>([]);

  useEffect(() => {
    fetch('htttp://localhost:5000/api/products')
      .then(response => response.json())
      .then(data => setProducts(data))
  },[])

  function addProduct() {
    setProducts(prevState => [...prevState,
      {
        id: prevState.length + 101,
        name: "product" + (prevState.length + 1),
        price: (prevState.length * 100) + 100,
        brand: 'some brand',
        description: 'some description',
        pictureUrl: 'http://picsum.photos/200',
      }])
}
 
  return (
    <div className="app">
      <h1>RESTORE</h1>
      <ul>
        {products.map(product=>(
          <li key={product.id}>{product.name} - {product.price}</li>
        ))}
      </ul>
      <button onClick={addProduct}>Add product</button>
    </div>
  );
}

export default App;

Program.cs

using API.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations.Operations;

internal class Program
{
    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        builder.Services.AddControllers();
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen();
        builder.Services.AddDbContext<StoreContext>(opt =>
        {
            opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
        });
        builder.Services.AddCors();
        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }
        app.UseCors(opt =>
        {
            opt.AllowAnyHeader().AllowAnyMethod().WithOrigins("http:/localhost:3000");

        });
        app.UseAuthorization();
        app.MapControllers();

        var scope = app.Services.CreateScope();
        var context = scope.ServiceProvider.GetRequiredService<StoreContext>();
        var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();

        try
        {
            context.Database.Migrate();
            DBInitializer.Initilize(context);
        }
        catch (Exception ex)
        {

            logger.LogError(ex, "A problem occurred during migration");
        }

        app.Run();
    }
}

我尝试检查我的Cors是否正确写入以及引用的本地端口是否正确。

reactjs asp.net-core cors
1个回答
0
投票

您需要添加Cors服务,然后配置中间件以使用指定的策略(或默认策略)。

以下是添加服务的方法,同时还将设置指定为默认设置:

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(
      policy =>
      {
          policy
          .WithOrigins("http:/localhost:3000")
          .AllowAnyHeader()
          .AllowAnyMethod();
      });
});

如果您好奇的话,添加的服务包括 CORS 服务本身、默认策略提供程序以及各种与选项相关的服务 然后,在管道中注册中间件:

// ...

var app = builder.Build();

app.UseRouting(); // i am not sure where this needs to be, since you are using a JS client. it might have to go after Cors middleware. Please edit this if you find out how where this line needs to go. for systems without JS clients, it goes before Cors middleware.

app.UseCors(); // you dont have to specify a policy name since you configured a default policy.

app.UseStaticFiles(); // this needs to go after cors middleware since you are using a JS client. this is confirmed at microsoft docs.

app.UseAuthorization();

// ...

中间件在后台使用通过DI添加的cors服务,因此需要使用

AddCors
将服务添加到服务容器中。

© www.soinside.com 2019 - 2024. All rights reserved.