Refused to set unsafe header "Origin" when using xmlHttpRequest of Google Chrome

Derrick LAU picture Derrick LAU · Jun 25, 2012 · Viewed 73.3k times · Source

Got this error message: Refused to set unsafe header "Origin"

Using this code:

   function getResponse() {
            document.getElementById("_receivedMsgLabel").innerHTML += "getResponse() called.<br/>";
            if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
                receiveReq.open("GET", "http://L45723:1802", true, "server", "server123");  //must use L45723:1802 at work.
                receiveReq.onreadystatechange = handleReceiveMessage;
                receiveReq.setRequestHeader("Origin", "http://localhost/");
                receiveReq.setRequestHeader("Access-Control-Request-Origin", "http://localhost");
                receiveReq.timeout = 0;
                var currentDate = new Date();
                var sendMessage = JSON.stringify({
                    SendTimestamp: currentDate,
                    Message: "Message 1",
                    Browser: navigator.appName
                });
                receiveReq.send(sendMessage);

            }
        }

What am I doing wrong? What am I missing in the header to make this CORS request work?

I tried removing the receiveReq.setRequestHeader("Origin", ...) call but then Google Chrome throws an access error on my receiveReq.open() call...

Why?

Answer

Brian S picture Brian S · Jun 25, 2012

This is just a guess, as I use jquery for ajax requests, including CORS.

I think the browser is supposed to set the header, not you. If you were able to set the header, that would defeat the purpose of the security feature.

Try the request without setting those headers and see if the browser sets them for you.