HTTP Endpoints CORS policy

Hi together,

I am currently trying to setup a https endpoint. The function should require application authentication. I simply setup a function and a https endpoint now that does nothing special so far and tried requesting it from the frontend with axios, however, I am getting an CORS error: “… has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

If I understand it correctly this issues appears since the OPTIONS request to my https endpoint does not include the access control allow origin header and therefore the actual GET request never gets executed.

My request looks as follows

await axios.get(
      "https://.../something",
      {
        headers: {
          username: "xyz",
          password: "safePassword"
        }
      }
    );

And in realm it is mostly the default function

// This function is the endpoint's request handler.
exports = function({ query, headers, body}, response) {
    // Data can be extracted from the request as follows:

    // Query params, e.g. '?arg1=hello&arg2=world' => {arg1: "hello", arg2: "world"}
    const {arg1, arg2} = query;

    // Headers, e.g. {"Content-Type": ["application/json"]}
    const contentTypes = headers["Content-Type"];

    // Raw request body (if the client sent one).
    // This is a binary object that can be accessed as a string using .text()
    const reqBody = body;

    console.log("arg1, arg2: ", arg1, arg2);
    console.log("Content-Type:", JSON.stringify(contentTypes));
    console.log("Request body:", reqBody);

    // You can use 'context' to interact with other Realm features.
    // Accessing a value:
    // var x = context.values.get("value_name");

    // Querying a mongodb service:
    // const doc = context.services.get("mongodb-atlas").db("dbname").collection("coll_name").findOne();

    // Calling a function:
    // const result = context.functions.execute("function_name", arg1, arg2);

    // The return value of the function is sent as the response back to the client
    // when the "Respond with Result" setting is set.
    response.addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
    response.addHeader("Access-Control-Allow-Methods","GET");
    response.addHeader( "Access-Control-Allow-Headers",  "Content-Type, username, password");
    response.setStatusCode(200);

    return  "Hello World!";
};

I hope someone can help to find what’s missing since this didnt seem to be an issue with the old webhooks.

BR

You might want to disable return type and do not return anything from your function. Instead, use
response.setBody(message);

1 Like