【问题标题】:how to send HTTP request with APIKEY如何使用 APIKEY 发送 HTTP 请求
【发布时间】:2020-09-28 08:35:59
【问题描述】:

我创建了一个 API 网关来触发我的 lambda 函数。我正在尝试保护调用 URL。我了解我们可以使用 Lambda Authorizer 或 APIKEY。我正在尝试使用 API 密钥,但不确定如何使用 fetch 传递 API 密钥。

我还将 API 与 API 密钥和使用计划相关联。

我正在尝试从客户端访问 URL。

invokeurl 指的是我的调用 URL,它将返回 JSON 对象。 egkeyname 是我无法分享的关键值。

客户端.py:

onMount(async () => {
    const res = await fetch('invokeurl',{
        method:'get',
        headers: new Headers ({
            'Access-Control-Allow-Origin' : '*',
            'Access-Control-Allow-Methods':'OPTIONS,POST,GET',
            'X-API-KEY' :'egkeyname' 
        })
    });  //wait until the promise return result
    data = await res.json();    
});

但我得到一个错误:

Access to fetch at '..invoke ur...' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

Uncaught (in promise) TypeError: Failed to fetch

GET https:invokeurl net::ERR_FAILED

我的 lambda 函数:

  responseObject = {}
  responseObject['statusCode'] = 200
  responseObject['headers']={}
  responseObject['headers']['Content-Type'] = 'application/json'
  responseObject['headers']['Access-Control-Allow-Origin'] = '*'
  responseObject['headers']['Access-Control-Allow-Methods'] = 'OPTIONS,POST,GET'
return responseObject

如何使用 APIkey 访问 URL?

【问题讨论】:

标签: fetch aws-api-gateway api-key


【解决方案1】:

我自己解决了。我在 Header 中使用了错误的信息。

应该是:

onMount(async () => {
    const res = await fetch('invokeurl',{
        method:'get',
        headers: new Headers ({
            'Access-Control-Request-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
            'Origin' : '*',
            'Access-Control-Request-Method':'OPTIONS,POST,GET',
            'X-API-KEY' :'egkeyname' 
        })
    });  //wait until the promise return result
    data = await res.json();    
});

【讨论】:

    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2014-12-24
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多