-1

when I tried URL from browser and postman its working fine and return response but when I tried Jquery AJAX its give me CROSS domain issue.

How can we avoid this CROSS domain issue while hitting API using AJAX

1 Answers1

0

Install CORS plugin in firefox and chrome, IE just handles it well. As other suggested, you are surely working in locale (with your localhost), so the CROSS origin request is a security policy common to new browsers. I don't know your backend but if it's in ajax I would write this :

 $.ajax({
            url: "http://localhost:8079/students/add/",
            type: "POST",
            crossDomain: true,
            data: JSON.stringify(somejson),
            dataType: "json",
            success: function (response) {
                var resp = JSON.parse(response)
                alert(resp.status);
            },
            error: function (xhr, status) {
                alert("error");
            }
        });

if your backend it's in php,you can add those lines :

 header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: X-Requested-With");
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

The CORS or CROSS Origin Request is just a security policy that fires mostly when you're developing on your pc, try to think if there was a malicious script and your browser didn't block the Cross Domain Request :
the malicious code could have injected your website code

Fedeco
  • 846
  • 10
  • 28