Slav Slav - 1 year ago 89
HTTP Question

CORS: policy differs if accessing URL from browser or from within script

If I access server right through browser's address field, server successfully responds.
But when I try accessing it from my send.js script:

var request = new XMLHttpRequest(); 'GET', "", true );
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8;");
request.onreadystatechange = function ()
document.write( "received response: " + request.response );
document.write( "sending request ..." );
request.send( 'login=billy&password=sunshines' );

accessing it through index.html over Mongoose local web server with browser:

<!DOCTYPE html>
<meta charset="utf-8">
<title>Server send script TEST</title>
<script src="send.js"></script>

It fails with error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.

Why CORS policy differs when I access page directly through browser's address field from when I access through locally hosted script? Am I missing some fields to specify for request?

Answer Source

When you access the script directly by using the address bar there is no cross origin resource sharing taking place. Your browser navigated to so any request to is same-origin.

When your browser location is, a request to is Cross-Origin because your browser location differs from the location to which you're making http requests.

You'll have to enable CORS on your backend or use JSONP.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download