首页 > 解决方案 > DevExtreme ODataStore Remove 方法 withCredentials 在 React 项目中不起作用

问题描述

我遇到了关于从 devextreme odatastore 中删除实体的问题。

我在本地有两个项目,后端项目在 localhost:54602 上运行,前端项目在 localhost:3000 上运行(react app)

我能够在没有 CORS 问题的情况下请求数据。(CORS 设置在后端进行)

但是当我尝试从 ODataStore 中删除一个实体并在调试模式下查看后端时

context.User.Identity.IsAuthenticated 变量更改为 false。并且请求失败。

Chrome 控制台输出在这里

从源“ http://localhost:3000 ”访问“ http://localhost:54602/units(3) ”处的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:重定向是不允许用于预检请求。

我阅读了有关 CORS Preflight 的所有链接

我的 CORS 设置在这里。

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        .
        .
        .
    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        .
        app.UseCors(options =>
            {
                options.WithOrigins("http://localhost:3000")
                .WithMethods("GET", "POST", "PUT", "PATCH", "POST", "DELETE", "OPTIONS")
                .AllowAnyHeader()
                .AllowCredentials();
            }
        );

        .
    }

在反应应用程序中,我正在创建像这样的 oDataStore

export default class extends React.Component {  

.
.
oDataStore = new ODataStore(
{
  key: 'Oid',
  version: 4,
  url: 'http://localhost:54602/units',
  withCredentials : true
});

.
.
}

最后删除这样的电话。

this.oDataStore.remove(this.state.selectedUnit.Oid).then(
                (key) => { 
                  alert(`${key} will be delete.`);
                },
                (error) => 
                { 
                  alert(`${error} occured.`);
                }
              );

任何帮助都会被接受。我期待着您的回复。

祝你今天过得愉快。

标签: c#reactjsasp.net-web-apicorsdevextreme

解决方案


我在后端服务器项目中跟踪了输出。

面对这一点,前端的 DELETE 请求首先发送 OPTIONS 请求,如此处所述

我目前正在使用这样的中间件。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   .
   .
   app.UseMiddleware<UnauthorizedRedirectMiddleware>();
   .
}

并像这样配置了 OPTIONS 请求。

public async Task InvokeAsync(HttpContext context)
    {
        if (context.Request.Method == "OPTIONS")
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:3000");
            context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            context.Response.Headers.Add("Access-Control-Allow-Methods", "DELETE");
            context.Response.Headers.Add("Access-Control-Allow-Headers", "content-type");
            context.Response.StatusCode = (int)HttpStatusCode.OK;
            return;
        }

        .
        .
        .
    }

2天没人回复。我被搜查了。

我希望这些信息可以节省您的时间。

有一个好的编码。


推荐阅读