代码之家  ›  专栏  ›  技术社区  ›  Shaun Roselt

在Delphi中使用MARS REST API库时,如何允许使用头字段(HeaderParam)?

  •  0
  • Shaun Roselt  · 技术社区  · 2 年前

    我使用 MARS-Curiosity Delphi REST Library 使用POST请求端点,并且该端点在中工作得非常好 Postman ,但一旦我尝试从其他地方(如JavaScript中)执行POST请求,就会收到一个CORS策略错误。

    我得到的正是:

    访问“”获取http://127.0.0.1:8080/rest/person/profile/get'来自原点'http://localhost'已被CORS策略阻止:飞行前响应中的访问控制允许标头不允许请求标头字段api_key。

    岗位 http://127.0.0.1:8080/rest/person/profile/get net::ERR_FAILED

    Access to fetch at 'http://127.0.0.1:8080/rest/person/profile/get' from origin 'http://localhost' has been blocked by CORS policy: Request header field api_key is not allowed by Access-Control-Allow-Headers in preflight response.

    我不知道如何允许或使用MARS中的标头。我试着看了一下演示,但没有发现任何有用的东西。

    这是我定义端点的Delphi代码:

    [Path('profile')]
    TPersonResource = class
    protected
    public
      [POST, Path('get'), Produces(TMediaType.APPLICATION_JSON)]
      function PersonProfileGet([HeaderParam] API_Key: String; [BodyParam] APerson: TPersonGet): TArray<TPersonGet>;
    end;
    

    你会看到我有 [HeaderParam] API_Key: String; 作为中的参数之一 PersonProfileGet 作用这是在一些 Demos 而且

    这是我用来尝试执行请求的JavaScript代码:

    const requestHeaders = {
        "Content-Type": 'application/json',
        "API_Key": "Test"
    };
    
    const requestOptions = {
      method: 'POST',
      headers: requestHeaders
    };
    
    fetch("http://127.0.0.1:8080/rest/person/profile/get", requestOptions)
      .then(response => response.text())
      .then(result => console.log(result))
      .catch(error => console.log('error', error));
    

    有人知道如何允许MARS中的头字段吗?或者为什么我会出现这个错误?

    1 回复  |  直到 2 年前
        1
  •  0
  •   Shaun Roselt    2 年前

    这其实很简单。

    有一个 .ini 文件与可执行文件位于同一文件夹中。它也应该与您的可执行文件具有相同的名称。

    如果在其中添加以下行:

    CORS.Headers=API_Key
    

    这将允许 API_Key 用作头字段之一。

    但在你的情况下, CORS.Headers 已经在那里,并且已经设置了一些允许的标头 Content-Type 被允许,但没有给出CORS策略错误。所以你只需要找到 CORS。页眉 然后添加 API_密钥 最后,如本例所示:

    CORS.Headers=Content-Type,API_Key
    
    推荐文章