Slaus
Slaus

Reputation: 2236

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();
request.open( 'GET', "myserver.com", 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>
<html>
<head>
    <meta charset="utf-8">
    <title>Server send script TEST</title>
</head>
<body>
<script src="send.js"></script>
</body>

It fails with error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.101:8080' 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?

Upvotes: 1

Views: 920

Answers (1)

sheepdog
sheepdog

Reputation: 625

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

When your browser location is http://192.168.0.101:8080, a request to myserver.com 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.

Upvotes: 2

Related Questions