1

I'm building a C++ backend with heavy calculations that are meant to work as an JSON API for connecting clients. To accomplish this, I've used HTTPServer in Poco::Net from POCO C++ Libraries.

Unfortunately when building two different clients it turned out that a regular webpage (HTML+JS) can't use Fetch to communicate with the backend due to CORS error. My understanding is that they need to use the same localhost: and that's not the case when manually opening the HTML document on the computer that's also running the backend.

All I can come up with when searching is the generic advice that servers need to enable CORS and whitelist relevant domains. Unfortunately I can't find documentation on how to accomplish this. The only relevant result was an answer on a related question where he recommended the following:

response.set("Access-Control-Allow-Origin", "*");

Naturally whitelisting everything isn't recommended from a security point of view but the main goal here is to just get it running locally to continue the development. Unfortunately it seems to make no difference and the browser console still says:

Access to fetch at 'http://localhost:6363/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

Hovering the error in the Chrome Network tab I get the following:

Cross-Origin Resource Sharing error: PreflightMissingAllowOriginHeader

My current JavaScript call:

const data = { test: 'test' }

fetch('http://localhost:6363', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
})
.then(response => response.text())
.then(message => {
    console.log('Data retrieved:', message);
})
.catch((error) => {
    console.error('Error:', error);
});

Any suggestions on how to proceed?

unknown83
  • 11
  • 2
  • Related: https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work – kiner_shah Apr 12 '22 at 11:38
  • You probably want to wrap your call to C++ API inside another local API. Something like `fetch('/postDataToCppAPI'...)` and then call C++ API from `/postDataToCppAPI`. – kiner_shah Apr 12 '22 at 11:44

0 Answers0