Search code examples
javascriptdelphicorspostmanfetch-api

How to enable CORS when using the MARS REST API Library with Delphi?


I made a very simple API with a very simple POST endpoint using the MARS-Curiosity Delphi REST Library and my endpoint is working perfectly fine in Postman, but as soon as I try to use the endpoint in JavaScript, then I get a CORS policy error.

Here's exactly what I get:

Access to fetch at 'http://localhost:8080/rest/person/profile/get' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

POST http://localhost:8080/rest/person/profile/get net::ERR_FAILED 200 (OK)

Access to fetch at 'http://localhost:8080/rest/person/profile/get' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I suspect this is because I don't have CORS Enabled in my Delphi MARS REST API, but how and where do I enable this?


For some added info, this is my exact code used to do the JavaScript Fetch:

const requestOptions = {method: 'POST'};

fetch("http://localhost:8080/rest/person/profile/get", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

Solution

  • This is actually a very simple fix.

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

    You simply need to make sure you have the following in that file:

    CORS.Enabled=True
    CORS.Origin=*
    CORS.Methods=HEAD,GET,PUT,POST,DELETE,OPTIONS
    CORS.Headers=X-Requested-With,Content-Type,Authorization
    

    And then CORS will be enabled for your MARS API and all your endpoints will also work.


    If you use the template that comes with the MARS API Library, then you should already have that in your .ini file, but it's just commented out and you can simply uncomment it. It'll look like this and you can just remove the semicolon (;):

    ;CORS.Enabled=True
    ;CORS.Origin=*
    ;CORS.Methods=HEAD,GET,PUT,POST,DELETE,OPTIONS
    ;CORS.Headers=X-Requested-With,Content-Type,Authorization