【问题标题】:CORS problems using React and Entity Framework Core 5 Web API [duplicate]使用 React 和 Entity Framework Core 5 Web API 的 CORS 问题 [重复]
【发布时间】:2021-07-27 06:07:00
【问题描述】:

同时非常感谢任何愿意帮助我的人。 我正在创建一个类似于 netflix 的应用程序,但我遇到了问题;我无法以任何方式正确启用 CORS(我的前端是使用 React 创建的,而我的 Web API 是使用实体框架核心 5 创建的)。 是不是我在.net core的Startup.js或者react的.env文件中写错了? 我在我的 .env 文件中设置的变量是根据邮递员地址设置的,除其他外,请愿书可以完美运行,我无法理解的是,似乎一切正常,但同时我什么都看不见。无论如何,我附在下面的 startup.cs 文件和 .env 文件,以使您了解我所写的内容并可能修复我的错误。

这是我的 Startup.cs 文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using microsquare.Context;
using microsquare.Services;
using microsquare.MiddleWares;
using Newtonsoft.Json;

namespace microsquare
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        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.AddControllers(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            }).AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            );
            services.AddScoped<IUserDataService, UserDataService>();
            services.AddCors(p =>
            {
                p.AddPolicy("MyPolicy",
                    builder =>
                    {
                        builder.AllowAnyHeader()
                            .WithOrigins("http://127.0.0.1:5000")
                            .WithMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS").Build(); 
                    });
            });
            
            var key = Encoding.ASCII.GetBytes(Configuration.GetValue<string>("SecretKey"));
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateLifetime =  true,
                    ValidIssuer = "",
                    ValidAudience = "",
                    ValidateAudience = false,
                    ValidateIssuer = false,
                    ValidateIssuerSigningKey= true
                };
            });
            
            //services.AddDbContext<ApiAppContext>(options => options.UseInMemoryDatabase("AppDB"));
            services.AddDbContext<ApiAppContext>(options => options.UseSqlServer(@"Data Source=DESKTOP-CF92CDJ;Initial Catalog=microsquare; Integrated Security=SSPI;"));
            
            services.AddResponseCaching();
            
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "microsquare",
                    Description = "An ASP.NET Core Web API",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact = new OpenApiContact
                    {
                        Name = "Alessandro Reina",
                        Email = string.Empty,
                        Url = new Uri("https://github.com/rei83/"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url = new Uri("https://example.com/license"),
                    }
                });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                //app.UseDeveloperExceptionPage();
                app.UseExceptionHandler("/error");
                
            } 
            else {
                    
            }
            
            app.UseSwagger(c =>
                {
                    c.SerializeAsV2 = true;
                });
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "microsquare v1");
                });
            
            
            app.UseHttpsRedirection();
            
            app.UseRouting();

            app.UseCors();
            
            app.UseResponseCaching();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                app.UseStatusMiddleWare();
            });
        }
    }
}

相反,这是我在 Ract 应用中创建的 .env.example 文件:

# Environmental Variables - EXAMPLE

REACT_APP_API_URL=http://localhost:5000
REACT_APP_API_USER=http://localhost:5000

然后,我真的无法理解的是,在我的浏览器控制台中,显然没有出现错误,但是当我尝试在我的 React 应用程序的“index.js”文件中分派一个类别时“正如我所说,包含在我的 API 中,我的浏览器的 Redux 选项卡中没有任何内容。

这是我的简单 index.js 文件:

import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/App'
import "./styles/styles.scss"
import store from './redux/store'
import { Provider } from 'react-redux'
import {getAllDocumentaries, getAllKids} from './redux/actionCreators'


store.dispatch(getAllDocumentaries)
store.dispatch(getAllKids)

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>
  , document.getElementById('root'));

提前感谢任何会帮助我的人

问候

亚历山德罗

【问题讨论】:

    标签: c# .net reactjs asp.net-core redux


    【解决方案1】:

    尝试用以下代码替换您的 CORS 代码:

     services.AddCors(o => o.AddPolicy("MyPolicy",
                        builder =>
                        {
                           builder.WithOrigins("http://localhost:5000")
                           .AllowAnyMethod()
                           .AllowAnyHeader();
                }));
    .....
    
        app.UseCors("MyPolicy");
    
    

    【讨论】:

      猜你喜欢
      • 2020-09-06
      • 2021-09-24
      • 2020-12-14
      • 2021-04-07
      • 2021-08-06
      • 2020-04-28
      • 2018-04-12
      • 2020-05-02
      • 1970-01-01
      相关资源
      最近更新 更多