首页 > 解决方案 > 在 Angular 应用程序中对 /index.html 进行 POST 调用时出现 500 内部服务器错误

问题描述

我正在开发一个角度应用程序。我正面临这个问题,我需要一些帮助来解决它。

当我对 http://<myapp>/index.html 执行 GET 操作时,它工作正常。
当我对 http://<myapp>/index.html 执行 POST 操作时,它返回500 Internal Server Error的响应正文或标头中没有任何内容。

我进行了调查RouterModule.forRootapp.module.ts但找不到任何POST单独过滤呼叫的选项。

这是我正在运行的 Asp.Net Core MVC 应用程序。

我是角度的新手。我不确定要走哪条路。任何帮助,将不胜感激。

谢谢。

标签: angularasp.net-core-mvcinternal-server-error

解决方案


我最近遇到了同样的问题,根据我的调查,代码的行为因环境而异(开发与生产)在开发中,如果你对 /index.html 进行 POST,你会得到 404,在生产中你会得到 500。我也提出了一个 GitHub 问题:https ://github.com/dotnet/aspnetcore/issues/34420

我的临时解决方案是添加一个中间件并捕获来自 UseSpa 中间件的异常

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ......
    app.Use(async (context, next) =>
    {
        //Redirect to root request to /index.html ( except the GET request ) 
        //Do not generate logs for requests originating from automated tools: POST /Index.html, OPTIONS /index.html, DEBUG /index.htm, etc.. 
        if (!HttpMethods.IsGet(context.Request?.Method)
            && context.Request?.Path.Value.ToLower() == "/index.html")
        {
            context.Response.Redirect("/");
            return;
        }

        try
        {
            await next();
        }
        catch (InvalidOperationException spaException)
        {
            if (spaException.Message.StartsWith("The SPA default page middleware could not return the default page"))
            {
                context.Response.StatusCode = StatusCodes.Status404NotFound;
                return;
            }
            throw;
        }
    });

    app.UseSpa(...);
    .....
}

推荐阅读