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

IT技术 reactjs asp.net-core asp.net-web-api axios cors
2021-05-16 19:45:38

我有一个 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;
};

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

更新:

这是我得到的 CORS 错误:

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

4个回答

试试这个:-

在你的 ConfigureServices

services.AddCors();

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

希望它能解决您的问题。

如果你有一个 create-react-app 项目,解决这个问题的方法是proxy在你的 package.json 文件中添加一个带有后端 url 的属性

{
...
   "proxy": "https://localhost:44376"
...
}

现在 yow 获取 url 必须是相对的

fetch("/api/users")

代替

fetch("https://localhost:44376/api/users")

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

请注意,CORS 预检请求(使用 HTTP OPTIONS 方法)用于检查 CORS 协议是否被理解,以及服务器是否使用特定的方法和标头。

并且 HTTP OPTIONS 请求始终是匿名的,如果您在本地项目上启用了 Windows 身份验证并禁用了匿名访问,这将导致 Web 服务器无法正确响应预检请求。

对于本地测试,可以先进行windows身份验证测试,然后通过允许匿名访问单独进行CORS测试。

Web API 使用 Windows 身份验证。部署到服务器时,我没有任何问题,但是当我尝试在本地运行应用程序时,出现 CORS 错误

如果已安装IIS CORS module并且为服务器上的应用程序/站点配置了 CORS 策略,或者为您的站点启用了 Windows 身份验证和匿名身份验证,这可能是应用程序可以在服务器上正常运行但无法正常运行的原因在本地 IIS 快递上。

您可以尝试添加如下:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
 ...
 app.UseCors(cors => cors.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
 app.UseAuthorization();
 ...
}

public void ConfigureServices(IServiceCollection services) {
 ...
 services.AddCors(c => { c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin()); });
 services.AddControllers();
 ...
}