Normally the backend and the frontend of a webapp run in different places.

For example in a test environment the frontend runs on localhost:80 in for example an Apache HTTP server and the backend runs in Matlab on port 8081.
When the website on localhost:80 calls the backend on port 8081 the following error can be observed in the Developer Console (Hit F12) of your browser.

What happens is that the browser blocks the cross site call because the Matlab backend does not allow by default calls from other sites than localhost:8081.

The remedy is simple: 

Add the Access-Control-Allow-Origin to the Matlab code with the value '*' to allow calls from any origin or a more specific value e.g. 'localhost:80' to only allow requests from the Apache HTTP server.

function JSONCallback(event)
% JSONCallback - Callback called by modelit.webserver.Server object for generating a
% JSON response.
%
% CALL:
%     JSONCallback(event)
%
% INPUT:
%     event: <modelit.webserver.HttpExchange>
%       with the request data and methods to generate a response.
%
% OUTPUT:
%     No output, a response with a JSON object is return to the client.
%
% EXAMPLE:
%  server = modelit.web.server.Server('localhost', 8081, @JSONCallback).start()
%
%  % Open a webbrowser and type: http://localhost:8081 in the address bar
%  % Now a json message appears in the browser.
%

%   Copyright 2020 Modelit, www.modelit.nl

% Generate the response
response = JSON(event);
% Set the MIME type and allow Cross Origin Resource Sharing
event.addResponseHeader('Content-Type', 'application/json',...
                        'Access-Control-Allow-Origin', '*');

% Send the response back to the client
event.send(200, response);

 

To reproduce this error run the code below in an Apache HTTP server

 

<!DOCTYPE html>
<html>
  <body>
    <div>
      <b>Time: </b><span id="time"></span>
      <br />
      <b>Method:</b><span id="method"></span>
      <br />
      <b>From:</b><span id="from"></span>
    </div>

    <script>
      document.addEventListener("DOMContentLoaded", (event) => {
        //the DOM is loaded

        function handler() {
          if (this.status == 200) {
            // success!
            let obj = JSON.parse(this.response);
            document.getElementById("time").innerHTML = obj.date;
            document.getElementById("from").innerHTML = obj.from;
            document.getElementById("method").innerHTML = obj.method;
          }
        }

        let client = new XMLHttpRequest();
        client.onload = handler;
        client.open("GET", "http://localhost:8081/json");
        client.send();
      });
    </script>
  </body>
</html>

 

And start the Matlab example HTTPCallback by executing: 

server = modelit.web.server.Server('localhost', 8081, @JSONCallback).start()