Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Blocked by CORS policy "...does not have HTTP ok status" (Amplify and ReactJS, AWS Gateway and Lambda)

I'm almost embarassed to be asking this question due to CORS support out there on SO but I can't get by:

Access to XMLHttpRequest at 'https://a93xxxxx.execute-api.eu-west-1.amazonaws.com/dev[object%20Object]' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I've even published my React project with Amplify and attempted it from the real domain name to even eliminate anything to do with the development environment (Cloud 9 running npm version 6.14.8)

I've also made a test running Chrome with the --disable-web-security flag.

My Lambda function contains the following (out of the box stub)

exports.handler = async (event) => {
// TODO implement
const response = {
    statusCode: 200,
//  Uncomment below to enable CORS requests
  headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers" : "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With",
      "Access-Control-Allow-Methods" : "OPTIONS,POST,GET,PUT"
    }

  , 
    body: JSON.stringify("Hello from Lambda!")
};
return response;
};

Note that I've uncommented the CORS request part and the response statusCode is set to 200. The code in my application that execute when a submission form is sent from the client:

    uploadcontactusdata = async data => {
    try {
        console.log("Contact Us pressed")
        const settings = {
            method: 'POST',
            body: JSON.stringify(data),
            
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }
        }

        const fetchResponse = await API.post('econtactus', settings);
        Notification({
            title: 'Success',
            message: 'Notification has been sent',
            type: 'success'
        });
    }
    catch (err) {
        console.log("unable to send");
        console.error(err)
    }
}

I created the API Gateway + Lambda using Amplify (version 4.41.2). Not sure where else to look now. Any clues will be appreciated. Thanks

question from:https://stackoverflow.com/questions/65835148/blocked-by-cors-policy-does-not-have-http-ok-status-amplify-and-reactjs-a

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

1 Reply

0 votes
by (71.8m points)

You can completely get past the need for api gateway by using appsync.

amplify add api

Choose graphql (I have not tried using rest but you shouldn't need it) choose the basic schema, edit it if you'd like, and publish. Once it's published you can create your own method. You can view this inside the AppSync UI under Schema.

type Mutation {
  yourMethod(input: Input!): TableName <-- add your method to the list
}

Now inside Appsync choose Data Sources and add datasource. Give it a name, choose lambda as the type, then find your lambda in the list. Once it's added go back to your schema and find the method you created above. On the right side bar locate your method and click the attach link. Find the data source you just added. Fill out the region and lambda ARN. MAKE SURE you choose new role and not an existing one.

You might need to configure the request and response templates.

For request:

{
  "version" : "2017-02-28",
  "operation": "Invoke",
  "payload": $util.toJson($context.args)
}

For response:

$util.toJson($context.result)

Now you can call your lambda directly from the UI and return your result without worrying about CORS or managing API Gateway.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...