无法通过Ajax调用AWS API Gateway [英] Cannot call aws API Gateway via ajax

查看:292
本文介绍了无法通过Ajax调用AWS API Gateway的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用aws APi网关和api网关自定义授权者。我为api网关自定义授权者提供的代码如下:

I am using aws APi gateway and api gateway custom authorizer. The code that I have for api gateway custom authorizer is as follows:

console.log('Loading function');

 exports.handler =  (event, context, callback) => {
var token = event.authorizationToken;
// Call oauth provider, crack jwt token, etc.
// In this example, the token is treated as the status for simplicity.

switch (token.toLowerCase()) {
    case 'allow':
        callback(null, generatePolicy('user', 'Allow', event.methodArn));
        break;
    case 'deny':
        callback(null, generatePolicy('user', 'Deny', event.methodArn));
        break;
    case 'unauthorized':
        callback("Unauthorized");   // Return a 401 Unauthorized response
        break;
    default:
        callback("Error: Invalid token"); 
}
};

var generatePolicy = function(principalId, effect, resource) {
var authResponse = {};

authResponse.principalId = principalId;
if (effect && resource) {
    var policyDocument = {};
    policyDocument.Version = '2012-10-17'; // default version
    policyDocument.Statement = [];
    var statementOne = {};
    statementOne.Action = 'execute-api:Invoke'; // default action
    statementOne.Effect = effect;
    statementOne.Resource = resource;
    policyDocument.Statement[0] = statementOne;
    authResponse.policyDocument = policyDocument;
}

// Can optionally return a context object of your choosing.
authResponse.context = {};
authResponse.context.stringKey = "stringval";
authResponse.context.numberKey = 123;
authResponse.context.booleanKey = true;
return authResponse;

这只是AWS网站中提供的一个简单的模拟示例。
然后,我使用此授权器在API网关中配置了get方法。同样在方法执行中,我添加了一个称为授权令牌的自定义hedear,将由授权者使用。

as you can see it is just a simple mock up example provided in aws website. Then I configured my get method in API gateway using this authorizer. Also in method execution I added a custom hedear called authorizationToken which will be used by authorizer.

当我使用邮递员时,一切都很好:

When I use the postman everything is good:

但是,当我尝试通过ajax进行如下调用时,出现以下错误:

However when I try to call it via ajax as follows I get the following error:

XMLHttpRequest cannot load https://590vv3bkda.execute-api.us-east-1.amazonaws.com/hamedstg/tjresource/story. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 401.

这是我的Ajax调用:

Here is my ajax call:

$.ajax(
    'https://590vv3bkda.execute-api.us-east-1.amazonaws.com/xxxxxxx',
    {
        method : 'GET',
        headers : {                                                                         
                      'authorizationToken' : 'allow'
                },
        beforeSend : function(xhr) {
            xhr.setRequestHeader('authorizationToken', 'allow');
        }
}).then(function(data) {
    console.log(data);
});

另外值得注意的是,我在aws的api上启用了CORS。

Also it is noteworthy that I enabled CORS on the api in aws.

有人可以帮忙吗?

推荐答案

自启用CORS以来,您是否添加了任何方法或资源?如果是这样,请再次运行CORS向导并重新部署到您的阶段。

Did you add any methods or resources since enabling CORS? If so, then run the CORS wizard again and redeploy to your stage.

此外,请确保您资源上的OPTIONS方法不需要/不使用客户授权者。选项必须向所有人开放,因为在某些情况下,浏览器会代表您调用它进行飞行前CORS检查。

Also, make sure that the OPTIONS method on your resource does not require/use the customer authorizer. OPTIONS needs to be open to all as the browser will call it on your behalf for pre-flight CORS checks in some cases.

还有一个已知的问题是由于任何原因,API网关调用都会由于任何原因而失败,未设置CORS标头,因此当根本原因完全不同时,您将收到不存在'Access-Control-Allow-Origin'标头错误。尝试打开浏览器的开发人员日志记录,获取发送到API的确切请求(它可能是OPTIONS方法),然后尝试与从API Gateway控制台进行测试调用相同的请求。这样一来,您就可以查看输出和日志,以确定是否还有其他问题。

There is also a known issue that when an API Gateway call fails for any reason, the CORS headers are not set and thus you'll get that "No 'Access-Control-Allow-Origin' header is present" error, when the root cause is something entirely different. Try turning on developer logging on your browser, get the exact request sent to the API (it may be an OPTIONS method) and try the same request as a test invoke from the API Gateway console. That will let you look at the output and the logs to determine if there is another issue.

这篇关于无法通过Ajax调用AWS API Gateway的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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