Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cors :) #5

Open
DenhamPreen opened this issue Jul 6, 2020 · 2 comments
Open

Cors :) #5

DenhamPreen opened this issue Jul 6, 2020 · 2 comments

Comments

@DenhamPreen
Copy link

Hi,
How do you enable cors?
https://www.npmjs.com/package/cors
I am familiar with this package for express. New to Reason so maybe its something simple. Appreciate any help.

@JasoonS
Copy link

JasoonS commented Jul 6, 2020

Hi I eventually solved this with a simple hack (we are literally using this in a hackathon 😬 )

(I only added that funcion setupCorsHack - the rest is your original code)

open Serbet;

let setupCorsHack = [%raw
  "app => {
    var cors = require('cors');
    app.use(cors());
  }"
];

let application = (~port=?, endpoints: list(endpoint)) => {
  let app = Express.App.make();
  let _ = setupCorsHack(. app);
  let router = Express.Router.make();
  app->Express.App.useRouter(router);

  endpoints->Belt.List.forEach(ep => {ep.useOnRouter(router)});

  let defaultPort =
    Node.Process.process##env
    ->Js.Dict.get("PORT")
    ->Belt.Option.map(a => Js.Float.fromString(a)->int_of_float)
    ->Belt.Option.getWithDefault(3000);

  let effectivePort = port->Belt.Option.getWithDefault(defaultPort);

  app->Express.App.listen(
    ~port=effectivePort,
    ~onListen=_ => {Js.log2("Server listening on port", effectivePort)},
    (),
  )
  |> ignore;

  {expressApp: app, router};
};

I know it is hacky, I'm just showing you what worked. The below didn't work:

  [@bs.module "cors"] external cors: (. unit) => Express.Middleware.t = "cors";

  let endpoint = collection =>
    Serbet.jsonEndpoint(
      ~middleware=[|cors(.)|],
      {
...etc etc

I actually have no idea why it didn't work.

Thanks in advance!

@mrmurphy
Copy link
Owner

mrmurphy commented Nov 8, 2020

Good question. I'm sorry I didn't see these issues before. I plan to release a new version of Serbet next week. And it'd be a good idea to add a section on using CORS to the docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants