ajax API 网关 CORS:没有“Access-Control-Allow-Origin”标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35190615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:29:28  来源:igfitidea点击:

API Gateway CORS: no 'Access-Control-Allow-Origin' header

ajaxamazon-web-servicescorsaws-api-gateway

提问by Tyler

Although CORS has been set up through API Gateway and the Access-Control-Allow-Originheader is set, I still receive the following error when attempting to call the API from AJAX within Chrome:

虽然已经通过 API Gateway 设置了 CORS 并设置了Access-Control-Allow-Origin标头,但在 Chrome 中尝试从 AJAX 调用 API 时仍然收到以下错误:

XMLHttpRequest cannot load http://XXXXX.execute-api.us-west-2.amazonaws.com/beta/YYYYY. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.

XMLHttpRequest 无法加载http://XXXXX.execute-api.us-west-2.amazonaws.com/beta/YYYYY。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'null'。响应具有 HTTP 状态代码 403。

I attempted to GET the URL through Postmanand it shows the above header is successfully passed:

我尝试通过Postman获取 URL ,它显示上述标头已成功传递:

Passed headers

传递的标题

And from the OPTIONS reponse:

来自 OPTIONS 的回复:

Response headers

响应头

How can I call my API from the browser without reverting to JSON-P?

如何在不恢复为 JSON-P 的情况下从浏览器调用我的 API?

回答by riseres

I get the same problem. I have used 10hrs to findout.

我遇到同样的问题。我已经用了 10 小时来找出答案。

https://serverless.com/framework/docs/providers/aws/events/apigateway/

https://serverless.com/framework/docs/providers/aws/events/apigateway/

// handler.js

'use strict';

module.exports.hello = function(event, context, callback) {

const response = {
  statusCode: 200,
  headers: {
    "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
    "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS 
  },
  body: JSON.stringify({ "message": "Hello World!" })
};

callback(null, response);
};

回答by Gabriel Doty

If anyone else is running into this still - I was able to track down the root cause in my application.

如果其他人仍然遇到这种情况 - 我能够在我的应用程序中找到根本原因。

If you are running API-Gateway with custom Authorizers - API-Gateway will send a 401 or 403 back before it actually hits your server. By default - API-Gateway is NOT configured for CORS when returning 4xx from a custom authorizer.

如果您使用自定义授权器运行 API-Gateway - API-Gateway 将在实际访问您的服务器之前发送 401 或 403。默认情况下 - 从自定义授权方返回 4xx 时,未为 CORS 配置 API 网关。

Also - if you happen to be getting a status code of 0or 1from a request running through API Gateway, this is probably your issue.

另外 - 如果您碰巧从通过 API Gateway 运行的请求获取状态代码01从其获取状态代码,这可能是您的问题。

To fix - in the API Gateway configuration - go to "Gateway Responses", expand "Default 4XX" and add a CORS configuration header there. i.e.

要修复 - 在 API 网关配置中 - 转到“网关响应”,展开“默认 4XX”并在那里添加 CORS 配置标头。IE

Access-Control-Allow-Origin: '*'

Make sure to re-deploy your gateway- and voila!

确保重新部署您的网关- 瞧!

回答by Carlos Alberto Schneider

1)I needed to do the same as @riseres and some other changes.This are my response headers:

1)我需要做与@riseres 和其他一些更改相同的事情。这是我的响应标头:

headers: {
            'Access-Control-Allow-Origin' : '*',
            'Access-Control-Allow-Headers':'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
            'Access-Control-Allow-Credentials' : true,
            'Content-Type': 'application/json'
        }

2) And

2和

According to this documentation:

根据此文档:

http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

When you use proxy for lambda functions on API Gateway config, the post or get methods have no added headers, only the options does. You must do it manually in the response(server or lambda response).

当您在 API Gateway 配置上为 lambda 函数使用代理时,post 或 get 方法没有添加标头,只有选项添加。您必须在响应(服务器或 lambda 响应)中手动执行此操作。

3) And

3) 和

Beside that, I needed to disable the 'API Key Required' option in my API gateway post method.

除此之外,我需要在我的 API 网关 post 方法中禁用“API Key Required”选项。

回答by MannyC

Got my sample working: I justinserted 'Access-Control-Allow-Origin': '*',inside headers:{}in the generated nodejs Lambda function. I made nochanges to the Lambda-generated API layer.

让我的示例工作:我刚刚在生成的 nodejs Lambda 函数中插入了'Access-Control-Allow-Origin': '*',inside headers:{}。我没有对 Lambda 生成的 API 层进行任何更改。

Here's my NodeJS:

这是我的 NodeJS:

'use strict';
const doc = require('dynamodb-doc');
const dynamo = new doc.DynamoDB();
exports.handler = ( event, context, callback ) => {
    const done = ( err, res ) => callback( null, {
        statusCode: err ? '400' : '200',
        body: err ? err.message : JSON.stringify(res),
        headers:{ 'Access-Control-Allow-Origin' : '*' },
    });
    switch( event.httpMethod ) {
        ...
    }
};

Here's my AJAX call

这是我的 AJAX 调用

$.ajax({
    url: 'https://x.execute-api.x-x-x.amazonaws.com/prod/fnXx?TableName=x',
    type: 'GET',
    beforeSend: function(){ $( '#loader' ).show();},
    success: function( res ) { alert( JSON.stringify(res) ); },
    error:function(e){ alert('Lambda returned error\n\n' + e.responseText); },
    complete:function(){ $('#loader').hide(); }
});

回答by lase

If you have tried everything regarding this issue to no avail, you'll end up where I did. It turns out, Amazon's existing CORS setup directions work just fine... just make sure you remember to redeploy! The CORS editing wizard, even with all its nice little green checkmarks, does not make live updates to your API. Perhaps obvious, but it stumped me for half a day.

如果您已经尝试了有关此问题的所有方法,但都无济于事,那么您最终会得到我所做的。事实证明,亚马逊现有的 CORS 设置指导工作得很好……只要确保你记得重新部署!CORS 编辑向导,即使有所有漂亮的小绿色复选标记,也不会对您的 API 进行实时更新。也许很明显,但它难倒了我半天。

enter image description here

在此处输入图片说明

回答by theaws.blog

For Googlers:

对于 Google 员工:

Here is why:

原因如下:

  • Simple request, or, GET/POSTwith no cookies do not trigger preflight
  • When you configure CORS for a path, API Gateway will only create an OPTIONSmethod for that path, then send Allow-Originheaders using mock responses when user calls OPTIONS, but GET/ POSTwill not get Allow-Originautomatically
  • If you try to send simple requests with CORS mode on, you will get an error because that response has no Allow-Originheader
  • You may adhere to best practice, simple requests are not meant to send response to user, send authentication/cookie along with your requests to make it "not simple" and preflight will trigger
  • Still, you will have to send CORS headers by yourself for the request following OPTIONS
  • 简单请求,或者,GET/POST没有 cookie 不会触发预检
  • 当您为路径配置 CORS 时,API Gateway 只会OPTIONS为该路径创建一个方法,然后Allow-Origin在用户调用时使用模拟响应发送标头OPTIONS,但GET/POST不会Allow-Origin自动获取
  • 如果您尝试在 CORS 模式下发送简单请求,您将收到错误消息,因为该响应没有Allow-Origin标头
  • 您可以遵循最佳实践,简单的请求并不意味着向用户发送响应,将身份验证/cookie 与您的请求一起发送以使其“不简单”并且预检将触发
  • 尽管如此,您仍必须为以下请求自行发送 CORS 标头 OPTIONS

To sum it up:

把它们加起来:

  • Only harmless OPTIONSwill be generated by API Gateway automatically
  • OPTIONSare only used by browser as a precautious measure to check possibilityof CORS on a path
  • Whether CORS is accepteddepend on the actual method e.g. GET/ POST
  • You have to manually send appropriate headers in your response
  • OPTIONSAPI Gateway 会自动生成无害的
  • OPTIONS仅被浏览器用作检查路径上 CORS可能性的预防措施
  • 是否接受CORS取决于实际方法,例如GET/POST
  • 您必须在响应中手动发送适当的标头

回答by RodP

I got mine working after I realised that the lambda authoriser was failing and for some unknown reason that was being translated into a CORS error. A simple fix to my authoriser (and some authoriser tests that I should have added in the first place) and it worked. For me the API Gateway action 'Enable CORS' was required. This added all the headers and other settings I needed in my API.

在我意识到 lambda 授权器失败并且由于某种未知原因被转换为 CORS 错误后,我开始工作。对我的授权人的简单修复(以及我应该首先添加的一些授权人测试)并且它起作用了。对我来说,API 网关操作“启用 CORS”是必需的。这在我的 API 中添加了我需要的所有标头和其他设置。

回答by Ziaur Rahman

Deploying the code after enabling CORS for both POSTand OPTIONSworked for me.

在为两者启用 CORSPOSTOPTIONS对我来说有效后部署代码。

回答by Vishal Shetty

I just added headers to my lambda function response and it worked like a charm

我刚刚在我的 lambda 函数响应中添加了标头,它就像一个魅力

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hey it works'),
        headers:{ 'Access-Control-Allow-Origin' : '*' }
    };
    return response;
};

回答by Ankit Kumar Rajpoot

After Change your Function or Code Follow these two steps.

更改您的功能或代码后 请按照以下两个步骤操作。

First Enable CORSThen Deploy APIevery time.

首先启用 CORS,然后每次都部署 API