Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enable CORS in Giraffe?

I am unable to successfully perform a Post operation using the Giraffe framework on the server with an Elm client sending the request.

I receive the following message when attempting to test an http request:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost1

  Request starting HTTP/1.1 OPTIONS http://localhost:5000/register  0 

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request

starting HTTP/1.1 OPTIONS http://localhost:5000/register 0 dbug: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware1

  OPTIONS requests are not supported

The service implementation is the following:

let private registrationHandler = 
    fun(context: HttpContext) -> 
        async {
            let! data = context.BindJson<RegistrationRequest>()
            match register data with
              | Success profile -> return! json profile context
              | Failure         -> return! (setStatusCode 400 >=> json "registration failed") context
        }

I then attempted the following and observed the same result:

let private registrationHandler = 
    fun(context: HttpContext) -> 
        async {
            return! text "hello world" context
        }

Appendix:

    POST >=> 
        choose [
            route "/register" >=> registrationHandler
        ]

The source file can be found here.

Elm and CORS

WebAPI enable Cors

Here's a Giraffe sample that shows the code for supporting Cors.

like image 704
Scott Nimrod Avatar asked Oct 19 '25 15:10

Scott Nimrod


1 Answers

  1. Add package: Microsoft.AspNetCore.Cors
  2. In .fs file add:
open Microsoft.AspNetCore.Cors
  1. Add UseCors e.g.:
let configureApp (app : IApplicationBuilder) =
    app.UseGiraffeErrorHandler errorHandler
    app.UseStaticFiles() |> ignore
    app.UseAuthentication() |> ignore
    app.UseCors(Action<_>(fun (b: Infrastructure.CorsPolicyBuilder) -> b.AllowAnyHeader() |> ignore; b.AllowAnyMethod() |> ignore)) |> ignore
    app.UseGiraffe webApp
  1. In services add cors:
let configureServices (services : IServiceCollection) =
let sp  = services.BuildServiceProvider()
let env = sp.GetService<IHostingEnvironment>()
let viewsFolderPath = Path.Combine(env.ContentRootPath, "Views")

services
    .AddCors()
    .AddAuthentication(authScheme)
    .AddCookie(cookieAuth)
    |> ignore
like image 159
Roman Motyka Avatar answered Oct 21 '25 03:10

Roman Motyka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!