CORs issue when using lambda function and Fetch API

I am running into an issue where the API is handling the fetch request ok but the browser still throws an error.

Here is my setup:

  • Redwood web on port 8910
  • Redwood API on port 8911
  • external project (serving via webpack on 8181)

On the external project I am calling the function like so

const onSubmit = (e) => {
  e.preventDefault();
  fetch("http://localhost:8911/feedback/", {
    method: "POST",
    body: JSON.stringify(
      {
        "text": text,
        "apiKey": props.apikey,
        "type": state.page
      }
    ),
  })
  .then((response) => {
    dispatch("home")
  });
}

When doing this

  • the browser complains about the CORS issue. Even though I handle the OPTIONS request.
  • the function request does work and the POST method is able to return. (I am creating a db row inside the handler).

Here is the modifications to the handler

export const handler = async (event, context) => {
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE'
  };

  if (event.httpMethod == "OPTIONS") {
    // To enable CORS
    return {
      statusCode: 200, // <-- Important!
      headers,
      body: ''
    };
  }

I have tried sending API request via http://localhost:8910/.netlify/functions/feedback/ and http://localhost:8911/feedback/. The API request works and the function completes. But the browser complains about a CORS issue.

I have managed to fix temporarily by using mode: ‘no-cors’ on fetch API. But this way no response is available for the browser.

Has anyone run into this before and know of a fix?

If any more info is needed, happy to provide.