简体   繁体   中英

Access-Control-Allow-Origin error

I'm using the following script -

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.9.1.min.js"></script>
<script>
function postForm() {

    $.ajax({
            type: 'POST',
            url: 'http://10.0.0.8:9000/demo',
            data: {"name" : "test"},
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
        })
    }

</script>
</head>
<body>
    <form id="ajaxForm" onsubmit="postForm(); return false; "  method="post"> 
        <input id="test" type="text" name="name" value="Hello JSON" /> 
        <input type="submit" value="Submit JSON" /> 
    </form>

</body>
</html>

The computer i'm trying to access is running the play framework. I am receiving the following error:

OPTIONS http://10.0.0.8:9000/demo 404 (Not Found) jquery-1.9.1.min.js:5 XMLHttpRequest cannot load http://10.0.0.8:9000/demo . Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.

I've been stumped now for two days, can anyone help me out?

Thanks ahead

The problem is that you're trying to make a cross-origin call (from http://localhost:8080 to http://localhost:9000 ). That's not allowed by the Same Origin Policy , so the browser is trying to use Cross-Origin Resource Sharing to ask the server if it's okay to allow the cross-origin call. (That's the OPTIONS HTTP request you're seeing.) Since the server doesn't reply to the OPTIONS request with headers allowing the call, it's denied by the browser for security reasons.

The SOP applies to all true "ajax" calls (eg, ones via XMLHttpRequest ). You can either:

  1. Update the server to implement the response to the OPTIONS request passing back the headers to allow the call (which will make it work on most modern browsers ), or

  2. Make the request to the same port (I'm guessing there's a reason you're not doing that), so the request is to the same origin and the SOP doesn't apply, or

  3. Switch over to using JSON-P . But JSON-P is inappropriate for form submissions because it's a GET , and GET operations are meant to be idempotent , which most form submissions aren't. So unless this happens to be an idempotent form submission (for instance, a search), using JSON-P would be a hack at best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM