Search code examples
javascripthttp-headerscorsfirebug

CORS header 'Access-Control-Allow-Origin' does not match... but it does‼


I'm making a very simple JSON API in Java. It's actually a Project Zomboid mod that serves object coordinates. This is how my HTTP handler looks like:

public class JSONZomboid implements HttpHandler
{
    @Override
    public void handle(HttpExchange t) throws IOException {
        // HEADERS
        Headers headers = t.getResponseHeaders();
        headers.set("Content-Type", "text/json");   
        headers.set("Access-Control-Allow-Origin", "pzmap.crash-override.net");                 
        t.sendResponseHeaders(200,0);
        //BODY
        OutputStream os = t.getResponseBody();
        os.write("{\n".getBytes());
          // generate JSON here
        os.write("}".getBytes());
        os.close();
    }
}

I want to load this into Project Zomboid map project using userscript which means I need to enable CORS to connect. This is done via simple code:

PlayerRenderer.prototype.fetchInfo = function() {
  $.get("http://127.0.0.1:8000/test", {}, this.displayPoints.bind(this));
}

But I get this error:

Warning: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/test. (Reason: CORS header 'Access-Control-Allow-Origin' does not match 'pzmap.crash-override.net').

Even in the console I can clearly see the error is misleading:

image description

If I didn't already hate CORS, I'd start to hate it now. Can you please tell me what is the actual string that belongs in the allow origin header?


Solution

  • The actual issue is that the Access-Control-Allow-Origin header should include the protocol, not just the hostname. It would be much better if the web browsers simply included this part in the error message.

    So in the above, do:

    headers.set("Access-Control-Allow-Origin", "http://pzmap.crash-override.net");