Search code examples
c#starcounter

Enable CORS in Starcounter


I am trying to send a browser request to my Starcounter app from a script in a website on another host. I get an error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . This can be fixed by moving the resource to the same domain or enabling CORS

What is the best way to enable CORS in a Starcounter app?


Solution

  • If you want to accept requests from other hosts in a web browser, you need to implement CORS. This is done the same way in Starcounter as in most other application frameworks.

    To accept GET requests or simple POST requests (with standard headers) from any host, you only need to add a response header Access-Control-Allow-Origin: * to your HTTP GET handlers. For example:

    Handle.GET("/myapp/some-page", () => {
      var page = new Json();
      var response = new Response();
      response.Resource = page;
      response.Headers["Access-Control-Allow-Origin"] = "*";
      return response;
    });
    

    To accept all requests that change something on the server (POST, PUT and DELETE), you should implement an OPTIONS preflight request handler to the same URI at your POST, PUT and DELETE handler. For example:

    Handle.PUT("/myapp/some-page", () => {
      var page = new Json();
      /* some logic ... */
      var response = new Response();
      response.Resource = page;
      response.Headers["Access-Control-Allow-Origin"] = "*";
      return response;
    });
    
    Handle.OPTIONS("/myapp/some-page", () => {
      var response = new Response();
      response.Resource = page;
      response.Headers["Access-Control-Allow-Origin"] = "*";
      response.Headers["Access-Control-Allow-Methods"] = "POST, PUT, GET, OPTIONS";
      response.Headers["Access-Control-Allow-Headers"] = "*";
      return response;
    });
    

    Read more about CORS at: - https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS - https://www.html5rocks.com/en/tutorials/cors/