Tomáš Zato Tomáš Zato - 6 months ago 55
Javascript Question

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
public void handle(HttpExchange t) throws IOException {
Headers headers = t.getResponseHeaders();
headers.set("Content-Type", "text/json");
headers.set("Access-Control-Allow-Origin", "");
OutputStream os = t.getResponseBody();
// generate JSON here

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("", {}, this.displayPoints.bind(this));

But I get this error:

warning Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at (Reason: CORS header 'Access-Control-Allow-Origin' does not match '').

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?


The comment #1 above is correct: CORS needs the Access-Control-Allow-Origin header to be match what the client's original request was (for an end-to-end SSL experience). So in this case, be sure you set in your Access-Control-Allow-Origin headers.

Two notes:

1- Despite what you may read online, nginx currently requires multiple entries to be listed as separate lines, a la: add_header Access-Control-Allow-Origin ""; add_header Access-Control-Allow-Origin "";

2 - Also despite what you may read online, usage of a wildcard is not ok. Not all clients (meaning browsers) allow it.