尽管在 Elm 和 Giraffe 中都启用了 CORS,但 Http Post 的问题

Issues with Http Post despite enabling CORS in both Elm and Giraffe

我一直在努力启用我的 Elm 客户端和 Giraffe 服务器之间的跨域请求。

榆树(客户端):

tryPostRegistration : String -> Http.Body -> Decoder JsonProfile -> Http.Request JsonProfile
tryPostRegistration url body decoder =
    Http.request
        { method = "POST"
        , headers =
            [ header "Origin" "http://elm-lang.org"
            , header "Access-Control-Request-Method" "POST"
            , header "Access-Control-Request-Headers" "X-Custom-Header"
            ]
        , url = url
        , body = body
        , expect = Http.expectJson decoder
        , timeout = Nothing
        , withCredentials = False
        }


tryRegister : Form -> (Result Http.Error JsonProfile -> msg) -> Cmd msg
tryRegister form msg =
    let
        url =
            baseUrl ++ "register"

        body =
            encodeRegistration form |> Http.jsonBody

        request =
            tryPostRegistration url body profileDecoder
    in
        Http.send msg request

错误(Elm 客户端):

HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).(XHR)OPTIONS - http://localhost:5000/register

长颈鹿(服务器):

let configureCors (builder : CorsPolicyBuilder) =
    builder.WithOrigins("http://localhost:5000").AllowAnyMethod().AllowAnyHeader() |> ignore

let configureApp (app : IApplicationBuilder) =
    app.UseCors configureCors |> ignore
    app.UseGiraffe webApp

let configureServices (services : IServiceCollection) =
    ...
    services.AddCors |> ignore // Enables CORS

错误(长颈鹿服务器):

dbug: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware1 OPTIONS requests are not supported

dbug: Giraffe.Middleware.GiraffeMiddleware[0] Giraffe returned Some for HTTP/1.1 OPTIONS /register

附录:

Elm Gateway (with CORS support)

Giraffe server (with CORS support)

Giraffe CORS sample project reference

let configureCors (builder : CorsPolicyBuilder) =
    builder.WithOrigins("http://localhost:5000").AllowAnyMethod().AllowAnyHeader() |> ignore

这个位表示“如果源是 http://localhost:5000,则允许​​跨源请求。但是,您似乎在默认端口上使用 elm-live,即 8000。如此有效,您的服务器是拒绝来自端口 8000 的请求。

长话短说,改成 http://localhost:8000。如果这不能解决问题,希望拥有实际 F# 知识的人能提供进一步的帮助。


headers =
    [ header "Origin" "http://elm-lang.org"
    , header "Access-Control-Request-Method" "POST"
    , header "Access-Control-Request-Headers" "X-Custom-Header"
    ]

这个位不会真正做任何事情 - 浏览器自己设置这些。 Elm 的 HTTP 库使用浏览器的 XMLHttpRequest 实现,而 XMLHttpRequest 不允许设置那些 headers,因此它们将被忽略。 https://fetch.spec.whatwg.org/#forbidden-header-namer 列出 headers 不允许您覆盖。

有时间多检查一下,但在您的代码或带有选项路由的 Giraffe 代码中找不到任何路由。在我使用的 C# Asp.Net 核心中:

    public IActionResult GetOptions()
    {
        Response.Headers.Add("Allow", "GET, OPTIONS, POST");
        return Ok();
    }

所以我认为您需要在 GET 上添加类似这样的内容:

route  "/options" >=> setHttpHeader "Allow" "GET, OPTIONS, POST"

我还没有尝试过长颈鹿,所以我无法测试这是否正确。