API网关CORS:无“ Access-Control-Allow-Origin”标头 [英] API Gateway CORS: no 'Access-Control-Allow-Origin' header

查看:532
本文介绍了API网关CORS:无“ Access-Control-Allow-Origin”标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管已通过API网关设置了CORS并设置了 Access-Control-Allow-Origin 标头,但在尝试调用API时仍然收到以下错误从Chrome中的AJAX中获取:


XMLHttpRequest无法加载



,然后从OPTIONS响应中:





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

解决方案

我遇到同样的问题。我用了10个小时才找到答案。



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

  // handler.js 

'使用严格';

module.exports.hello =函数(事件,上下文,回调){

const response = {
statusCode:200,
标头:{
Access-Control-Allow-Origin: *,// CORS支持才能正常工作
Access-Control-Allow-Credentials:true // Cookie,授权标头必须HTTPS
},
正文:JSON.stringify({ message: Hello World!})
};

回调(null,response);
};


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

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.

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

And from the OPTIONS reponse:

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

解决方案

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

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);
};

这篇关于API网关CORS:无“ Access-Control-Allow-Origin”标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆