首页 > 解决方案 > 启用 Cors NetCore React 前端

问题描述

我正在创建一个像 primevideo 这样的网络应用程序;在使用 Entity Framework C, core 5 构建 API 后,我开始使用 React 构建前端,但问题马上就出现了。虽然 API 结构没有出现任何错误,并且 postman 上的请愿书执行得很好,但我无法启用 CORS,就好像一切正​​常但我的浏览器控制台什么也没看到,我不知道我是否能想到什么是我的问题。我尝试了许多替代方案,但没有得出任何结论。我在下面附上 Startup.js 和 .env 文件提前感谢任何能给我宝贵帮助的人,我为我的英语道歉。

启动.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 System.Web.Http.Cors;
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.AddCors(p =>
            {
                p.AddPolicy("MyPolicy",
                    builder =>
                    {
                        builder.AllowAnyHeader()
                            .WithOrigins("https://127.0.0.1:3000")
                            .AllowAnyMethod().Build(); 
                    });
            });

            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);

            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>();
            
            
            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=LAPTOP-VPRJI708;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.UseResponseCaching();

            app.UseCors();


            app.UseAuthentication();

            app.UseAuthorization();

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

.env.example

# Environmental Variables - EXAMPLE

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

如果有用的话,我还会附上 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 } from './redux/actionCreators'
import { getAllKids } from './redux/actionCreators'


store.dispatch(getAllKids)

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

我再次感谢愿意帮助我的人

再会

亚历山德拉

标签: c#.netreactjsasp.net-coreredux

解决方案


您的来源是 http://localhost:5000,而不是https://127.0.0.1:3000。所以试试这个:

 builder.WithOrigins("https://127.0.0.1:3000")
        .AllowAnyHeader()
        .AllowAnyMethod(); 

 app.UseCors("MyPolicy");

推荐阅读