AWS API Gateway No 'Access-Control-Allow-Origin' header is present

后端 未结 5 1644
长发绾君心
长发绾君心 2020-12-05 00:31

I\'m stuck on an issue with API gateway and I\'ve gone through all the other SO answers on this, AWS forums and have been through their docs but still no joy.

I am t

相关标签:
5条回答
  • 2020-12-05 00:40

    If this is still not working for you, be sure to JSON.stringify() your json object if you are using $.ajax. If not, you will still be returned an error that claims to be a CORS-related error. But if you send the same json object using Postman, the request will succeed. Try it out...

    0 讨论(0)
  • 2020-12-05 00:44

    Digitalkapitaen's answer is correct; here is the code to save someone the trouble of looking up how to set an HTTP response header in Lambda:

    exports.handler = function(event, context, callback) {
        callback(null, {
            "statusCode": 200,
            "headers": { 
                "Access-Control-Allow-Origin": "*" 
            }
        });
    };
    
    0 讨论(0)
  • 2020-12-05 00:46

    For someone looking to integrate @Digitalkapitaen's solution in Flask, here's the code below:

    app = Flask(__name__)
    cors = CORS(app, resources={r"/*": {"origins": "*"}})
    
    @app.route("/")
    def helloWorld():
      return "Hello, cross-origin-world!"
    

    Do install the flask-cors module by doing a:

    pip install -U flask-cors
    
    0 讨论(0)
  • 2020-12-05 00:48

    The response for the GET request to the Lambda function must also contain the Access-Control-Allow-Originheader.

    0 讨论(0)
  • 2020-12-05 00:59

    In case you want to change only one header instead of replacing all headers as is shown in Words Like Jared answer. You can use this code:

    'use strict';
    
    module.exports.handler = (event, context, callback) => {
      const response = event.Records[0].cf.response;
      const headers = response.headers;
    
      headers['access-control-allow-origin'] = [{ key: 'Access-Control-Allow-Origin', value: "*" }];
    
      return callback(null, response);
    };
    

    Another examples can be found on Adding HTTP Security Headers Using Lambda@Edge and Amazon CloudFront. It works same for normal Lambda function.

    0 讨论(0)
提交回复
热议问题