Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

javascript - 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

question from:https://stackoverflow.com/questions/65876897/cross-origin-for-amazon-lambda-function-from-localhost-in-gatsby-site

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your headers look ok to me. (note: If you mix HTTP and HTTPS you are most likely to get a mixed content error in the client). If it is ONLY a CORS issue that you are seeing in the console in the web browser, then you might not have configured the API Gateway correctly in AWS.

In AWS, go to API Gateway and you should see something like the below: enter image description here

Make sure that you enable CORS and then redeploy.

UPDATE: Just looking at a previous implementation of a lambda function I setup with AWS. The headers I declared were as follows:

headers: {        
  "Content-Type" : "application/json",
  "Access-Control-Allow-Origin" : "*",
  "Allow" : "GET, OPTIONS, POST",
  "Access-Control-Allow-Methods" : "GET, OPTIONS, POST",
  "Access-Control-Allow-Headers" : "*",
  "Access-Control-Allow-Credentials" : true
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...