陳昱辰
陳昱辰

Reputation: 61

request api gateway cors error

I created a AWS API GATEWAY,and following aws doc totur step create api and Enable CROS and Deploy !

Enable CORS

✔ Create OPTIONS method

✔ Add 200 Method Response with Empty Response Model to OPTIONS method

✔ Add Mock Integration to OPTIONS method

✔ Add 200 Integration Response to OPTIONS method

✔ Add Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin Method Response Headers to OPTIONS method

✔ Add Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin Integration Response Header Mappings to OPTIONS method

✔ Add Access-Control-Allow-Origin Method Response Header to POST method

✔ Add Access-Control-Allow-Origin Integration Response Header Mapping to POST method

Your resource has been configured for CORS. If you see any errors in the resulting output above please check the error message and if necessary attempt to execute the failed step manually via the Method Editor.

Get an error message when I used this api:

XMLHttpRequest cannot load https://xxxxxxx.amazonaws.com/xxxx/xxxx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:7076' is therefore not allowed access. The response had HTTP status code 400.

What step should I've been done?

Upvotes: 1

Views: 3031

Answers (2)

陳昱辰
陳昱辰

Reputation: 61

Finally i found what happen in my error! The payload sent from AJAX to API Gateway is not in JSON format, but LAMBDA's input supports only JSON-formatted data, which causes LAMBDA to not process the input normally. This in turn led to a mistake in LAMBDA's operation.

When this happens, API GATEWAY will not receive a normal response, so it will not return 'Access-Control-Allow-Origin' to the client (AJAX), so there will be no HTTP The wrong head.

This problem is resolved after i've processed the payload using the JSON.stringify () function.

Upvotes: 1

siomes
siomes

Reputation: 181

I've got similar problems recently and assuming you've deployed your API:

enter image description here

and assuming again you are using some js client like jQuery, you may take in mind some POST/GET parameters:

HTTP GET Request

$.ajax({
  crossDomain : true,
  contentType : 'application/json',
  method : "GET",
  url : YOUR_API_GATEWAY_URL,
  dataType : "json"
}).done(...)

HTTP POST Request

$.ajax({
   data : JSON.stringify({
     param1 : val1,
     param2 : val2,
     ...
   }),
   crossDomain : true,
   contentType : 'application/json',
   method : "POST",
   url : YOUR_API_GATEWAY_URL,
  dataType : "json"
}).done(...) 

Upvotes: 0

Related Questions