阅读背景:

对AWS API网关访问发出请求

来源:互联网 

I have a AWS Lambda function that is triggered via AWS API Gateway. When I test my function on Lambda it is working. When I send a POST request to the API url via ajax, I get a 502 bad gateway error.

我有一个AWS Lambda函数,它是通过AWS API网关触发的。当我测试我的函数时,它是有效的。当我通过ajax向API url发送POST请求时,会得到一个502错误的网关。

XMLHttpRequest cannot load https://xxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/myLambdaFunction. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'mywebsite.com' is therefore not allowed access. The response had HTTP status code 502.

XMLHttpRequest不能加载https://xxxxxxxx.execute api.us amazonaws.com/prod/mylambdafunction——东- 1.。在请求的资源上不存在“访问控制允许起源”的标头。因此,原产地“mywebsite.com”是不允许访问的。响应的HTTP状态码为502。

Obviously this was a CORS issue, so I thought I could change the CORS settings in my AWS API Gateway URL which I did, but I am still getting an error for this.

显然这是一个CORS问题,所以我想我可以在我的AWS API网关URL中修改CORS设置,我做了,但是我仍然得到一个错误。

What do I have to change on AWS side or my own to be able to POST to the URL?

我需要在AWS方面或我自己上更改什么才能发布到URL?

2 个解决方案

#1


2  

Unfortunately there is a known issue with many classes of 4xx and 5xx errors where CORS headers will not be sent, even if you've added CORS support via the console.

不幸的是,有一个已知的问题,即许多类的4xx和5xx错误不会发送CORS header,即使您已经通过控制台添加了CORS支持。

As noted in comments, the CORS error is a side effect of the fact that your API is returning a 502. This often occurs if you are using the LAMBDA_PROXY integration type and are returning invalid JSON from your Lambda function.

正如注释中所指出的,CORS错误是一个事实的副作用,您的API正在返回一个502。如果您使用的是LAMBDA_PROXY集成类型,并且从Lambda函数中返回无效的JSON,通常会出现这种情况。

Please try either using the test invoke functionality from the console or enable logging in your API to debug further.

请尝试使用来自控制台的测试调用功能,或者在您的API中启用日志记录以进一步调试。

#2


0  

I solved that exact same problem by outputting the CORS header myself. See below - and I hope that'll help. Teebo

我通过自己输出CORS的头来解决同样的问题。请看下面——我希望这能有所帮助。Teebo

Amazon docs

亚马逊文档

function respond(context, responseData) {
var response = {
  statusCode: 200,
  body: JSON.stringify(responseData),
  headers: {
    "Content-Type": "application/json; charset=utf-8",
    "Access-Control-Allow-Origin": "*"
  }
};
context.succeed(response); }

分享到: