request api gateway cors error

空扰寡人 提交于 2020-01-07 05:04:23

问题


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?


回答1:


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.




回答2:


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

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(...) 


来源:https://stackoverflow.com/questions/46314573/request-api-gateway-cors-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!