I have an application written in React JS, running on localhost, which makes API calls to API Gateway in AWS. API Gateway forwards requests to a lambda function, which returns a response. I have enabled CORS on AWS side. At the moment whenever I click a 'request' button in the application I get a response from the gateway. Here is my current python code:
import json def lambda_handler(event, context): response = {} response['result'] = "Success" response['message'] = "Updated successfully!" return { 'headers': { 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST' }, "body": json.dumps(response) } And here's the body of the request:
{ "ID": "1101", "RequestDate": "2021-02-28" } This works fine. I get the 'message' value from this response and can display it without problems. Next I want to display the information containing some data coming from the request. For example instead of Updated successfully I would like to get the RequestDate from the request and return Updated successfully on 2021-02-28. I added these two lines:
def lambda_handler(event, context): body = json.loads(event['body']) request_date = body['RequestDate'] response = {} response['result'] = "Success" response['message'] = "Updated successfully!" return { 'headers': { 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST' }, "body": json.dumps(response) } As soon as I make this change I get the following code in my application:
Access to fetch at url from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. This only happens when I add request_date = body['RequestDate']. I tried returning the body only and it was working fine as well.
In my react js application I add following headers as well:
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } I tried enabling CORS and deploying the resource again but to no avail. I have added Access-Control-Allow-Origin to allowed headers in AWS. As I mentioned it works fine with post method prior to adding that one line. What could be wrong here and how can I remedy it?
没有评论:
发表评论