javascriptdelphicorsfetch-apirequest-headers

How to allow header field (HeaderParam) when using the MARS REST API Library with Delphi?


I've made a basic API using the MARS-Curiosity Delphi REST Library with a POST Request Endpoint and this endpoint is working perfectly fine in Postman, but as soon as I try to do the POST Request from somewhere else such as within JavaScript, then I get a CORS policy error.

Here's exactly what I get:

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.

POST 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.

I am not sure how to allow or use headers within MARS. I tried looking at the demos, but I didn't find anything helpful.

This is my Delphi code where I define the endpoint:

[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;

You'll see I have [HeaderParam] API_Key: String; as one of the parameters in the PersonProfileGet function. This is how it is done in some of the Demos also.

And this is the JavaScript code I am using to try and do the request from:

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

Does anyone know how to allow header fields in MARS or why I'm getting this error?


Solution

  • This is actually very simple.

    There's a .ini file in the same folder as your executable. It should also have the same name as your executable.

    If you add the following line in there:

    CORS.Headers=API_Key
    

    This will allow API_Key to be used as one of the header fields.

    But in your case, CORS.Headers is already in there with some allowed headers already set seeing that Content-Type was allowed and didn't give a CORS policy error. So you just need to find CORS.Headers and then add API_Key at the end of it, like in this example:

    CORS.Headers=Content-Type,API_Key