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?
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.
In CORS the calling code doesn't have to do any special configuration. Everything should be handled by the browser. It's the server's job to decide if request should be allowed or not. So any time you are making a request which breaks SOP policy, the browser will try to make a CORS request for you (it will add Origin header automatically, and possibly make a preflight request if you are using some unsafe headers/methods/content types). If the server supports CORS it will respond properly and allow/disallow the request by providing CORS specific response headers like
Access-Control-Allow-Origin: *
Keep in mind that Chrome is very restrictive about 'localhost' host name. (At least it was when I was working with it). Instead use your computer name or assign it another alias in 'hosts' file. So for example don't access your site like:
http://localhost:port/myappname
Instead use:
http://mymachinename:port/myappname
or
http://mymachinealias:port/myappname
For more details please check specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With