如何使用 ASP.NET Core 解决 REACT 中的 CORS 错误

2023-11-25

我有一个 ASP.NET Core Web API 和一个单独的 React 应用程序。 Web API 使用 Windows 身份验证。当部署到服务器时,我没有任何问题,但是当我尝试在本地运行应用程序时,我会收到 CORS 错误,并且仅在 POST 操作上出现。这是我的Startup.cs:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Server.DAL;
using Server.Data;

namespace Server
{
    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.AddDbContext<AppDbContext>(options => options
               .UseSqlServer(Configuration.GetConnectionString("DatabaseConnection"))
               .UseLazyLoadingProxies());

            services.AddScoped<IUnitOfWork, UnitOfWork>();

            services.AddControllers();

            services.AddCors(options => options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder
                    .WithOrigins("http://localhost:3000")                        
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                }));    
        }

        // 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.UseSwagger();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors("CorsPolicy");

            app.UseAuthorization();

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

而且,这是我在 React 应用程序中的 axios 配置:

import axios, { AxiosInstance } from "axios";

let axiosInstance: AxiosInstance;

const axiosBaseConfig = {
  baseURL: process.env.REACT_APP_BASE_URL,
  timeout: 1000 * 20,
  withCredentials: true,
  headers: {
    Accept: "applicaiton/json",
    "Content-Type": "application/json",
  },
};

export const getAxios = () => {
  if (axiosInstance) {
    return axiosInstance;
  }

  axiosInstance = axios.create(axiosBaseConfig);

  return axiosInstance;
};

我在这里遗漏或做错了什么吗?

UPDATE:

这是我收到的 CORS 错误:

从源“http://localhost:3000”访问“https://localhost:44376/api/reservation”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:值响应中的“Access-Control-Allow-Credentials”标头为“”,当请求的凭据模式为“include”时,该标头必须为“true”。 XMLHttpRequest 发起的请求的凭据模式由 withCredentials 属性控制。


尝试这个:-

In your ConfigureServices

services.AddCors();

和你的配置方法app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000"));

希望它能解决您的问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 ASP.NET Core 解决 REACT 中的 CORS 错误 的相关文章

随机推荐