Saturday 30 January 2021

cross origin for amazon lambda function from localhost in gatsby site

I have the following code which works when I run it as a local serverless function with netlify dev, but I need it to run cross origin from a dev server to the hosted server function. I put the function in a aws lambda function but I am getting a cross origin blocked error on my https:dev.website.com, I thought I have the correct headers in the return object so not sure why I am getting a cross origin error.

Any help would be great

const sanityClient = require("@sanity/client");
const client = sanityClient({
  projectId: "random-id",
  dataset: "production",
  useCdn: true,
});

exports.lambdaHandler = async (event, context) => {
  var body = JSON.parse(event.body);

  //console.log(body.price_id)

  try {
    const checkPriceId = async (test) => {
      const query = `*[_type == "products" && price_id == "${body.price_id}"]`;

      const documents = await client.fetch(query, {}); // this could throw

      return documents.map((document) => document.sold);
    };

    var ok = checkPriceId().then((test) => {
      return new Promise(function (resolve, reject) {
        //console.log(test) // this will log the return value from line 7
        console.log(test);
        resolve(test);
      });
    });

    var bools = await ok;
    // prettier-ignore

    return {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Allow-Methods':'GET, POST, OPTION',
      },
      body: JSON.stringify({
        sold: bools,
      }),
    };
  } catch (err) {
    return { statusCode: 500, body: err.toString() };
  }
};

This is my request to the function if that helps

 var fetchUrl = https://random.executue-api.aws.com/prod/sold //not exact 

 var fetchData = async function () {
    const response = await fetch(fetchUrl, {
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        price_id: final,
      }),
    })
      .then(res => {
        return res.json()
      })
      .catch(error => console.log(error))

    return response
  }

Update:

I tried adding cors the way suggested in the answer below, but it failed seen below so I tried manually adding the method response seen after.

I still get a cross domain error. And I have changed the domain so it is now https as well. Really stuck here.

cors failing

manual cors addition

I was looking into this more, and it seems like before it does the actual post it does a cors check at the options method, so I added in the same access control headers, and deployed but did not work. Don't quite get this.

enter image description here



from cross origin for amazon lambda function from localhost in gatsby site

No comments:

Post a Comment